[英]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. https://en.cppreference.com/w/cpp/algorithm/set_difference我想找出两张地图的不同之处——只需比较钥匙。
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.效果很好,并找到了“ttt”。 But my real second type is a heavy type instead of an int.
但我真正的第二种类型是重类型而不是 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:如果您只想存储由
set_difference
生成的对的键,则可以使用 range-v3 库:
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>>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.