MrSparkly
MrSparkly

Reputation: 639

C++: iterating over a list and an unordered_map in one loop

In c++, I have a list of wstrings and an unordered wstring/wstring map.

std::list<std::wstring> m_L;
std::unordered_map<std::wstring, std::wstring> m_UM;

I need to run a loop over both lists and I don't want to repeat the loop code (in the unordered map, I only care about the first wstrings, not the second ones). Is there an iterator construct that would allow me to iterate over these two types in one loop? If I try to do this, I get "cannot deduce auto type" on auto* n:

for (auto* n : { &m_L, &m_UM }) {
    for (auto& it : *n) {
        ...

Upvotes: 1

Views: 205

Answers (1)

Fureeish
Fureeish

Reputation: 13424

With C++20's ranges (or with range-v3 library) you can do that rather trivially:

int main() {
    std::list<std::string> l_str = {"a", "b", "c"};
    std::unordered_map<std::string, std::string> m_str = {{"d", "dd"}, {"e", "ee"}};

    using namespace ranges::views; // for concat(), all() and keys()
    for (auto& e : concat(all(l_str), keys(m_str))) {
        std::cout << e << ' ';
    }
}

Output: a b c e d.


Note that I replaced std::wstring with std::string, but that should not make any real difference in the demonstration.

Upvotes: 3

Related Questions