简体   繁体   中英

A more effective way to apply std::set_difference for std::map

https://en.cppreference.com/w/cpp/algorithm/set_difference I want to find the differences of 2 maps -- just by comparing the keys.

map<string, int> m1 = { {"abc", 1},{"ttt", 2}, {"ccc", 3}, };
map<string, int> m2 = { {"abc", 3},{"bbb", 2}, {"ccc", 3}, };

std::vector<std::pair<string, int>> diff;
std::set_difference(m1.begin(), m1.end(), m2.begin(), m2.end(), std::inserter(diff, diff.begin()),
    [](auto& a, auto& b) { return a.first < b.first; });

for (auto& dif : diff)
{
    cout << dif.first << endl;
}

That works well and finds "ttt" out. But my real second type is a heavy type instead of an int.

std::vector<std::pair<string, heavyType>> diff;

Storing the heavyType is low performance. Is there a better way to achieve the result with high performance?

If you just want to store the keys of the pairs produced by set_difference , you can use the range-v3 library:

namespace rv = ranges::views;

auto diff = rv::set_difference(m1, m2, [](auto& a, auto& b) { 
                                             return a.first < b.first; 
                                       }) 
          | rv::keys
          | ranges::to<std::vector<std::string>>;

Here's a demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM