Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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.

like image 578
Aminos Avatar asked Aug 28 '16 12:08

Aminos


2 Answers

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;
        });
}
like image 71
michalsrb Avatar answered Oct 12 '22 23:10

michalsrb


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) {}
like image 30
for_stack Avatar answered Oct 12 '22 23:10

for_stack