Search code examples
c++structcomparemaps

Compare a struct in a map


I want to map a struct(key) to an int(value). Then I want to find a value given a key (struct).

typedef struct {
  int  a, b; 
} TechId;  

struct our_cmp {
  bool operator() ( TechId a, TechId b ) const
  { return std::make_pair(a.a,a.b) > std::make_pair(b.a, b.b) ; }

};

int main() {
std::map<TechId, int, our_cmp> mymap;

TechId x;

if(mymap.find(x)) {
  printf("found");
}

}

There is a find function but I guess it is only for string/ints etc? Is there a possibility to adapt it to my struct?


Solution

  • You need to check the iterator returned by find with the end() iterator of the map. If they are not equal, the element you searched for was found:

    if (mymap.find(x) != mymap.end()) {
        printf("found");
    }
    

    Since C++20, you could also use the contains member function to do the same thing:

    if (mymap.contains(x)) {
        printf("found");
    }