How to find whether an element exists in std::map?

后端 未结 11 2201
醉梦人生
醉梦人生 2020-12-07 23:55

My use case:

map cars;
bool exists(const string& name) {
  // somehow I should find whether my MAP has a car
  // with the name provid         


        
11条回答
  •  难免孤独
    2020-12-08 00:40

    Apart from the answers with iterator-Value from find() and comparison to .end(), there is another way: map::count.

    You can call map::count(key) with a specific key; it will return how many entries exist for the given key. For maps with unique keys, the result will be either 0 or 1. Since multimap exists as well with the same interface, better compare with != 0 for existence to be on the safe side.

    for your example, that's

    return (cars.count(name)>0);
    

    The advantages I see are 1. shorter code, 2. benefit from whatever optimisations the library may apply internally, using its representation details.

提交回复
热议问题