Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a set_difference vector from two maps

Tags:

c++

c++11

stl

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.

like image 932
jignatius Avatar asked Apr 20 '26 13:04

jignatius


1 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.)

like image 74
Brian Bi Avatar answered Apr 22 '26 02:04

Brian Bi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!