I’m wondering if only by applying some standard algorithms is possible to write a short function which compares two std::map<string, string> and returns true if all the key-value (but some) pairs are true.
For example, these two maps should be evaluated as equal
map<string,string> m1, m2;
m1["A"]="1";
m2["A"]="1";
m1["B"]="2";
m2["B"]="2";
m1["X"]="30";
m2["X"]="340";
m1["Y"]="53";
m2["Y"]="0";
Suppose that the two maps have same size and all their elements must be pairwise compared except the value stored by the key "X" and key "Y". A first attempt would be a very inefficient double nested for loop.
I’m sure a better solution can be achieved.
I am not sure what exactly you are looking for, so let me first give complete equality and then key equality. Maybe the latter fits your needs already.
Complete Equality
(While standard equivalence can be tested using
std::map‘s own comparison operators, the following can be used as a base for a comparison on a per-value basis.)Complete equality can be tested using
std::equalandstd::operator==forstd::pairs:Key Equality
C++2003
Based on the above code, we can add a predicate to the
std::equalcall:C++ (C++11)
Using the new lambda expressions, you can do this:
C++ (C++14)
added 2014-03-12
Using the new generic lambda expressions, you can do this:
As a style-matter, you can also inline the lambda expressions in C++11 and C++14 directly as a parameter: