0

I have C++ code like this:

if(rtstructure.find(varName) != rtstructure.end()) {
    rtdef = rtstructure[varName];
}

where rtstructure is std::map with std::string for the key. This code works but it seems like a waste to make it search twice for the same key. If I omit the if case around the assignment, the program crashes if varName points to a key that doesn't exist.

Can I in a single map operation look up a key in a std::map and get its value if it exists, without crashing if it doesn't exist?

3
  • 1
    Your program shouldn't usually crash. Do you use map<K,V*> by any chance? Also note that map::find returns an iterator, you can happily use the value notion of the iterator (second) Commented Nov 24, 2013 at 22:38
  • Yes the map is std::map<std::string, rtobject_t*> rtstructure; where rtobject_t is a struct. Commented Nov 25, 2013 at 10:37
  • So apparently, the [] operator returns a new uninitialized pointer if referring to a member that doesn't exist. Commented Nov 25, 2013 at 16:59

1 Answer 1

5

find give you a std::map<>::iterator that holds/point to std::pair<>. The iterator can be saved and reused (given that you did not do anything to invalidate it such as erase).

// i don't know the type of rtstructure so i use auto
// you can replace it to the correct type if C++11 is not available
auto it = rtstructure.find(varName); 
if(it != rtstructure.end()) {
    rtdef = it->second;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.