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

后端 未结 11 2156
醉梦人生
醉梦人生 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:43

    Sure, use an iterator

    map<string,Car>::const_iterator it = cars.find(name);
    return it!=cars.end();
    
    0 讨论(0)
  • 2020-12-08 00:46

    This does not answer the question but it might be good to know. You can know if it exists by erasing it.

    bool existed = cars.erase( name );
    
    0 讨论(0)
  • 2020-12-08 00:47

    You could also use

    bool exists(const string& name) {
      return cars.count(name) != 0;
    } 
    
    0 讨论(0)
  • 2020-12-08 00:51
    return cars.find(name) != cars.end();
    
    0 讨论(0)
  • 2020-12-08 00:55

    C++20:

    return cars.contains(name);
    
    0 讨论(0)
提交回复
热议问题