简体   繁体   English

如何通过键和值比较两个映射并将差异映射存储在c ++中的结果映射中? 我们有任何Stl API吗?

[英]How to compare two maps by both key and value and storing difference map in resultant map in c++? Do we have any stl api for it?

Do we have any stl function to compare and store difference between map like set_difference or is there a way to use set_difference? 我们是否有任何stl函数来比较和存储map之间的差异(如set_difference),或者有没有办法使用set_difference? If anyone has a logic to compare both value or key of two maps with less complexity will be much appreciated. 如果有人有逻辑比较两个地图的值或键,而复杂度较低,将不胜感激。 Note: Using C++ 注意:使用C ++

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

int main()
{
    std::map<int, double> square    = {{0, 0.0}, {1, 1.0}, {2, 4.0}};
    std::map<int, double> fibonacci = {{0, 0.0}, {1, 1.0}, {2, 1.0}};
    std::vector<std::pair<int, double>> result;
    std::set_difference(begin(square), end(square), begin(fibonacci), end(fibonacci), std::back_inserter(result));

    for (auto p : result) {
        std::cout << p.first << " => " << p.second << "\n";
    }
    // prints 2 => 4 as expected
}

std::set_difference is perfectly usable with std::map . std::set_differencestd::map完全可用。 Full demo: http://coliru.stacked-crooked.com/a/02cc424fa0e5aba0 完整演示: http : //coliru.stacked-crooked.com/a/02cc424fa0e5aba0


And for fun: 为了好玩:

template<class Container>
auto operator-(Container lhs, Container rhs)
{
    std::vector<typename Container::value_type> result;
    std::set_difference(cbegin(lhs), cend(lhs), cbegin(rhs), cend(rhs), std::back_inserter(result));
    return result;
}
auto result = square - fibonacci;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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