vote up 1 vote down
star

Q: How would I determine if a "key" exists in a map?

Context: Im making an image manager that has a single function that takes a string paramater that is the file folder/file name of the image file.

Example: Image& Ret(string FileName)

I want it to return a reference to the image that has been stored in memory. The function will have a dual purpose of being a "setter" and "getter." The map is so the keys will be the FileName. How would I go about determining if map[FileName] exists? I tried using find() but it returns an iterator and I tried evaluating it as NULL but it didnt work, so im kind of lost as to how I would check it or if there is a better way.

Thank you! :)

flag

2 Answers

vote up 1 vote down

You need to simply check if the iterator returned is == the end of the map. If it is, then the key wasn't found.

if (map.find("key") == map.end() )
{
    // Didn't Find it
}
link|flag
Yes, you cannot check the result for null because it returns an iterator pointing at the .end() on failure to find. However, I'm not sure what you could reasonably return on error since you are returning a reference. – Chad Stewart Oct 27 at 16:38
vote up 0 vote down

Do you mean this?

struct Image
{
    Image(int a) : a(a) {}
    int a;
};

int main()
{
    map<string, Image> images;
    images.insert(make_pair("Five", Image(5)));
    images.insert(make_pair("Ten", Image(10)));
    cout << images.find("Five")->second.a << endl;
}
link|flag
That simply prints the value of a key. If Five didn't exist then that code would fail. – resolveaswontfix Oct 27 at 13:32
Oh, sorry. I didn't read the question properly. – Martin Oct 27 at 13:53

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.