Aminos Aminos - 3 months ago 37
C++ Question

how to easily check if a std::map and std::unordered_map contains the same elements

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 crtierion. The order is not important.

Answer

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.begin(), map.end(), [&](std::pair<K, E> item) {
            auto iter = unordered_map.find(item.first);
            return iter != unordered_map.end() && iter->second == item.second;
        });
}
Comments