Reputation: 12266
I have the following structure:
std::map<int, std::map<int, int>> my_map;
I want to check whether the key my_map[3][5]
exists.
Is there any easier/shorter way to do so except for something like:
if (my_map.find(3) != my_map.end()) {
std::map<int, int>& internal_map = my_map[3];
if (internal_map.find(5) != internal_map.end()) {
// ... Do something ...
}
}
Upvotes: 2
Views: 964
Reputation: 21748
You could use this:
int k = 3;
int k1 = 5;
std::map<int, int>::iterator it = my_map[k].end();
if( (my_map.find(k))->second.find(k1) != it ){
std::cout << "something";
}
Upvotes: 0
Reputation: 9527
You could improve it a little via:
std::map<int, std::map<int, int>>::iterator it = my_map.find(3);
if (it != my_map.end()){
if (it->second.find(5) != internal_map.end()) {
}
}
In your current solution, you are finding the key twice and it could be slower than finding it once and store it in iterator.
Upvotes: 5