簡體   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?

我們是否有任何stl函數來比較和存儲map之間的差異(如set_difference),或者有沒有辦法使用set_difference? 如果有人有邏輯比較兩個地圖的值或鍵,而復雜度較低,將不勝感激。 注意:使用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_differencestd::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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM