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

后端 未结 3 1583
遥遥无期
遥遥无期 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::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
    }
    

提交回复
热议问题