Reputation: 21
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++
Upvotes: 1
Views: 1083
Reputation: 40070
#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;
Upvotes: 3