C ++ check if an object exists on two maps

I have my own object

class my_object
{
  int id;
  bool state;
  string name;
  string vendor;
}

And I would like to keep my object in two mapfor fairly quick reference.

std::map<string, my_object> map1;
std::map<string, my_object> map2;

Finally, I want to check if there are any keys of my object on both maps:

for(each my_object m1 in map1 and my_object m2 in map2 have the same key)
//for example, key "Bob" have corresponding objects in map1 and map2
{
  if(m1.vendor == m2.vendor)
  {
    //do some work
  }
}

How can I achieve a comparison job on two maps? Or should I use a different data structure?

UPDATE: Thanks for the answers. Why do I use two cards, because two different functions will create cards:

function1() //returns map1;
function2() //returns map2;

The key used on both cards is the namemy_object field . For a β€œfast enough link”, I thought that if map1 has n elements, map2 has m elements, is this computation time n * m?

+4
source share
3 answers

for (const auto& m1 : map1) {
    auto i2 = map2.find(m1.first);
    if (i2 != map2.end() && m1.second.vendor == i2->second.vendor) {
        // do some work
    }
}
+4

( , ), ( std::map::find).

for (const auto& kv : map1)
{
    auto it2 = map2.find(kv.first);
    if (it2 != map2.end() && kv.second.vendor == it2->second.vendor)
        ...do whatever...
}
+3

Here is a program that will call an arbitrary function for each key that exists on both cards. It is based on an example implementation of std :: set_intersection .

You can change the lambda to run an equality test vendoror any other test you want.

 #include <map>
 #include <string>
 #include <iostream>

 template<typename K, typename V1, typename V2, typename Func>
 void map_intersection(std::map<K,V1> const &m1, std::map<K,V2> const &m2, Func f)
 {
    auto it1 = m1.begin(), it2 = m2.begin();

    while (it1 != m1.end() && it2 != m2.end() ) {
         if (it1->first < it2->first) {
             ++it1;
         } else  {
             if (!(it2->first < it1->first)) {
                 f(it1->second, it2->second);
             }
             ++it2;
         }
     }  
 }

 int main()
 {
     std::map<std::string, std::string> map1 = { {"a", "apple"}, {"b", "bug"}, {"c", "car"} };
     std::map<std::string, std::string> map2 = { {"b", "boat"}, {"c", "car"} };

     map_intersection(map1, map2, [](std::string const &v1, std::string const &v2)
     {
         std::cout << "Same key: " << v1 << "," << v2 << '\n';
     });
 }

Conclusion:

Same key: bug,boat
Same key: car,car
+1
source

All Articles