Hello,
Would anybody suggest any STL algorithm that works on two ranges applying a predicate.
For example I would like to have the difference of two maps values.
Thanks in advance
Hello,
Would anybody suggest any STL algorithm that works on two ranges applying a predicate.
For example I would like to have the difference of two maps values.
Thanks in advance
A quick, practical follow-up to the replies from and : the core issue when working "pairwise" on two maps is alignment. Algorithms like the single-call two-range overloads assume element-by-element correspondence; that only holds for maps if both maps contain exactly the same keys in the same order. For a robust solution that computes value differences by key, a merge-style scan over the two ordered maps is simple, fast and correct.
template<typename Map>
Map map_difference(const Map& a, const Map& b) {
Map out;
auto ia = a.begin();
auto ib = b.begin();
while (ia != a.end() && ib != b.end()) {
if (ia->first < ib->first) {
++ia;
} else if (ib->first < ia->first) {
++ib;
} else {
out.emplace(ia->first, ia->second - ib->second);
++ia; ++ib;
}
}
return out;
} The above returns entries only for keys present in both maps in O(n) time (linear in the total size). If the desired result should include every key from the first map (treating missing keys in the second as zero), use a find-based loop instead — simpler but O(n log n) for ordered maps:
template<typename Map>
Map map_difference_with_zero(const Map& a, const Map& b) {
Map out;
for (const auto& kv : a) {
auto it = b.find(kv.first);
typename Map::mapped_type rhs = (it == b.end()) ? typename Map::mapped_type{} : it->second;
out.emplace(kv.first, kv.second - rhs);
}
return out;
} Notes and troubleshooting: ensure the mapped_type supports subtraction (or provide a custom binary op), watch numeric overflow and floating-point epsilons, and prefer the merge scan for ordered maps when both containers are large. If using unordered_map, use the find-based variant because there is no order to exploit. If attempting a two-range algorithm like std::transform, make sure the ranges truly align and the output iterator is valid; otherwise the merge/find approaches above are safer.
Jump to Post— vijayan121 1,152predicate versions of
std::mismatchstd::searchstd::lexicographical_comparestd::equaletc.
predicate versions of std::mismatch std::search std::lexicographical_compare std::equal etc.
#include <algorithm>
#include <functional>
...
transform(
a.begin(),
a.end(),
b.begin(),
result.begin(),
minus <pair <foo, bar> > ()
); You'll have to define what the difference between two pairs<> is... (by overloading the - operator)
Hope this helps.
Thanks, you have helped me much:)
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.