2

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 ... } } 
6
  • 1
    For one, you can use count() instead of find. Commented Nov 1, 2015 at 13:59
  • I have more than one key in the primary map and more than 1 key in the internal map Commented Nov 1, 2015 at 14:01
  • That doesn't matter. Commented Nov 1, 2015 at 14:08
  • Oh - count() means count of a specific key? But this is a map - the count can be only 0 or 1, am I wrong? Don't new values with same key override the former ones? Commented Nov 1, 2015 at 14:10
  • 1
    You're checking whether an item exists in a map, and count does exactly that. Yes, it can only be 0 or 1 for a map or set. It's the same complexity as find, may or may not be a tad faster (it doesn't have to construct an iterator). Commented Nov 1, 2015 at 14:14

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there something more simple in manners of code? Or we have code the checking of both maps? (like you and me have already done)
Depends what you want from it. Instead of two keys, you can use std::tupple (C++11) or std::pair as your key and have only one map
0

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"; } 

4 Comments

Thank you. What will happen if k is not a key in the primary map? Is it ok that you try to reach ->second and its method? Can't it be some undefined object?
this is UB if k does not exist
my English is not very good, but your question is correct, if I prove not exist, and the compiler, permitting, i was reading this cplusplus.com/reference/map/map/find this parte return value An iterator to the element, if an element with specified key is found, or map::end otherwise. cplusplus.com/reference/map/map/end I think there should be no problem, because compared with != it1, before using I also wondered the same thing and no probem tube, but I'm not an expert,
I just thought this might help, but it can be a response that causes some unwanted behavior I delete

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.