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

标签 c++ stl

我们是否有任何 STL 函数来比较和存储 map 之间的差异,例如 set_difference,或者有没有办法使用 set_difference? 如果有人有逻辑来比较两个 map 的值或键且复杂性较低,将不胜感激。 注意:使用 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 可与 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;

关于c++ - 如何通过键和值比较两个映射并将差异映射存储在 C++ 的结果映射中?我们有它的任何 STL api 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49980574/

相关文章:

c++ - 在 C++0x 中是否有类似 static_assert 的东西给出警告而不是错误?

c++ - 使用CMake构建C++项目时,链接Crypto++失败

c++ - 使用 std::set_intersection 时,哪个集合用于将值复制到目标集合中?

c++ - C++ 中的分配器用法(STL 树)

c++ - 调用带有字符串参数的函数直接与变量

c++ - 在 TensorFlow 存储库之外构建 TensorFlow C++ 项目?

c++ - wininet.dll 中看似随机崩溃的原因?

c++ - 分配包含 STL vector 的结构时发生内存泄漏

c++ - 在 dll 之间使用 STL 时遇到问题

c++ - std::wstring:与 + 的连接无效