How to check if std::map contains a key without doing insert?

后端 未结 3 1570
遥遥无期
遥遥无期 2020-12-04 08:26

The only way I have found to check for duplicates is by inserting and checking the std::pair.second for false, but the problem is that this still i

相关标签:
3条回答
  • 2020-12-04 08:54

    Potatoswatter's answer is all right, but I prefer to use find or lower_bound instead. lower_bound is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.

    map<K, V>::iterator iter(my_map.lower_bound(key));
    if (iter == my_map.end() || key < iter->first) {    // not found
        // ...
        my_map.insert(iter, make_pair(key, value));     // hinted insertion
    } else {
        // ... use iter->second here
    }
    
    0 讨论(0)
  • 2020-12-04 08:57

    Your desideratum,map.contains(key), is scheduled for the draft standard C++2a. In 2017 it was implemented by gcc 9.2. It's also in the current clang.

    0 讨论(0)
  • 2020-12-04 09:03

    Use my_map.count( key ); it can only return 0 or 1, which is essentially the Boolean result you want.

    Alternately my_map.find( key ) != my_map.end() works too.

    0 讨论(0)
提交回复
热议问题