I am writing a Google Test unit test, and I want to check if the content of an unordered_map<std::string, std::string>
is the same as an std::map<std::string, std::string>
I don't think std::equal
will work, as elements in the std::map
are sorted according a criterion. The order is not important.
I don't think there is nicer way than just going over all elements of one map and checking if they are present in the other map. If you also check that the amount of elements is the same, you'll know whether the maps are completely the same.
For example:
template<typename K, typename E>
bool maps_equal(const std::map<K, E> &map, const std::unordered_map<K, E> &unordered_map) {
return
map.size() == unordered_map.size() &&
std::all_of(map.cbegin(), map.cend(), [&](const std::pair<const K, E> &item) {
auto iter = unordered_map.find(item.first);
return iter != unordered_map.end() && iter->second == item.second;
});
}
You can create an unordered_map
with a map
, and then compare two unordered_map
. And vice versa.
std::unordered_map<std::string, std::string> m1;
std::map<std::string, std::string> m2;
std::unordered_map<std::string, std::string> m3(m2.begin(), m2.end());
if (m1 == m3) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With