简体   繁体   中英

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? If anyone has a logic to compare both value or key of two maps with less complexity will be much appreciated. Note: Using 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 . Full demo: 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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