I have my own object
class my_object
{
int id;
bool state;
string name;
string vendor;
}
And I would like to store my object into two map
for fast enough reference.
std::map<string, my_object> map1;
std::map<string, my_object> map2;
Finally, I want to check if there are some keys of my object exist in 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 the compare job in two maps? Or should I use a different data structure?
UPDATE: Thanks for the replies. Why I am using two maps is because two different function will produce the maps:
function1() //returns map1;
function2() //returns map2;
The key used in the both maps is the name
field of my_object. For "fast enough reference", I thought that if map1 has n elements, map2 has m elements, is my computation time n*m?
You can
for (const auto& m1 : map1) {
auto i2 = map2.find(m1.first);
if (i2 != map2.end() && m1.second.vendor == i2->second.vendor) {
// do some work
}
}
You can iterate over one of the maps (ideally you'd pick the shorter one if the number of elements could vary markedly and performance mattered), and while doing so search for each key in turn in the other map (with 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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With