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

时间:2018-04-23 11:59:18

标签: c++ stl

我们是否有任何stl函数来比较和存储set_difference等地图之间的差异,或者有没有办法使用set_difference? 如果有人有逻辑来比较两个地图的价值或关键,复杂性较低,将非常感激。 注意:使用C ++

1 个答案:

答案 0 :(得分:2)

#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完全适用于std::map。完整演示:http://coliru.stacked-crooked.com/a/02cc424fa0e5aba0

为了好玩:

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;
相关问题