Getting an error when checking if a key exists in a map

1
2
3
4
5
6
7
sf::Texture* TextureManager::GetTexture(std::string name)
{
	if (!textures.count[name])
		std::cout << "Could not get texture [" << name << "]." << std::endl;
	else
		return textures[name];
}


Error is on line 3: "Error C2677: binary '[' : no global operator found which takes type 'std::string' (or there is no acceptable conversion)"

How the key is delcared:
std::map<std::string, sf::Texture*> textures;
1
2
3
4
5
6
7
8
if (textures.find(name) == textures.end())
{
   std::cout << "Could not get texture [" << name << "]." << std::endl;
}
else
{
   return textures[name];
}
Why does not my code work?

Also, changing that code gave me an error in another function?
1
2
3
4
5
6
7
8
9
10
11
12
void TextureManager::AddTexture(std::string new_name, std::string new_location)
{
	sf::Texture * texture;

	if (!texture->loadFromFile(new_location))
	{
		std::cout << "could not load texture [" << new_name << "]." << std::endl;
		delete texture;
	}
	else
		textures[new_name] = texture;
}

line 5: "error C4700: uninitialized local variable 'texture' used"

Last edited on
the function does not know of texture.
you would need add a texture parameter to your function.
the function does not know of texture.
So what is on the line 3?

Problem is that it is illegal to call any member function on pointer which is not pointing to the valid object.

You should create object beforehand:
sf::Texture * texture = new sf::Texture;
kong288 wrote:
Why does not my code work?

From: http://www.cplusplus.com/reference/map/map/count/
size_type count (const key_type& k) const;
Note the parentheses.
In other words, line 3 of your original post should be
if (!textures.count(name))
Solution with find is faster and more readable.
oh wow, that's embarrassing. i guess my brain isn't working today. thanks for the help.
Solution with find is faster and more readable.

With a multimap it would be faster, but with map<>, count() returns 0 or 1 so I think the speed is comparable. It might even be faster since you don't have to do the check against end().

But the point about readability trumps any possible small performance gain. Checking find() != end() will work with most (all?) collections so it's what a reader would expect to see.
Topic archived. No new replies allowed.