Create a set_difference vector from two maps

Viewed 459

Currently I am getting the set difference of two maps and then iterating through the resulting map.

Ideally I want to create a vector of the difference instead of a map. That way I iterate more efficiently.

typedef std::map<int, Info> RegistrationMap;

RegistrationMap redundantRegs;
std::set_difference(map1.begin(), map1.end(), map2.begin(), map2.end(), 
std::inserter(redundantRegs, redundantRegs.begin()),
    [](const std::pair<int, Info> &p1, const std::pair<int, Info> &p2 {return p1.first < p2.first;});

for (auto reg : redundantRegs)
{
    map2[hiu.first].Status = "delete";
}

How would you create a vector of the set difference instead? Can this be done within the set_difference function?

I'm looking for the most efficient way possible of getting the difference.

2 Answers

std::set_difference can write its output to any output iterator, so there is no problem with writing the output into a vector:

std::vector<std::pair<int, Info>> redundantRegs;
std::set_difference(map1.begin(), map1.end(), map2.begin(), map2.end(),
                    std::back_inserter(redundantRegs),
                    ...);

(Note: In your comparator, change std::pair<int, Info> to std::pair<const int, Info> to avoid unnecessary copies.)

You can use std::set_difference but instead of std::inserter you better use std::back_inserter as that is most efficient on std::vector, and create std::vector accordingly:

std::vector<RegistrationMap::value_type> redundantRegs;;
std::set_difference(map1.begin(), map1.end(), map2.begin(), map2.end(), 
                    std::back_inserter(redundantRegs) );

Note: in the way you wrote it you do not need to write comparator explicitly, default one will work just fine. If you do not use default one, you better get it from the std::map using std::map::value_comp() instead of writing it explicitly as sorting criteria must match for map and std::set_difference:

std::set_difference(map1.begin(), map1.end(), map2.begin(), map2.end(), 
                    std::back_inserter(redundantRegs),
                    map1.value_comp() );

Live example

Related