How to iterate over a collection of key-value pairs (associative array) in C++

3 Answers

0 votes
// Iterate Over Key–Value Pairs

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> dict{
        {"Alice", 10},
        {"Bob", 17},
        {"Marley", 23},
        {"Charlie", 36}
    };

    for (const auto& [key, value] : dict) {
        std::cout << key << " = " << value << "\n";
    }
}



/*
run:

Alice = 10
Bob = 17
Charlie = 36
Marley = 23

*/

 



answered Mar 22 by avibootz
0 votes
// Iterate without Structured Bindings

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> dict{
        {"Alice", 10},
        {"Bob", 17},
        {"Marley", 23},
        {"Charlie", 36}
    };

    for (const auto& kvp : dict) {
        std::cout << kvp.first << " = " << kvp.second << "\n";
    }
}



/*
run:

Alice = 10
Bob = 17
Charlie = 36
Marley = 23

*/

 



answered Mar 22 by avibootz
0 votes
// Iterate and filtering With std::ranges (C++20)

#include <iostream>
#include <ranges>
#include <map>

int main() {
    std::map<std::string, int> dict{
        {"Alice", 10},
        {"Bob", 17},
        {"Marley", 23},
        {"Charlie", 36}
    };

    for (const auto& [key, value] : dict | std::views::filter([](auto& kvp) {
            return kvp.second > 21;
        }))
    {
        std::cout << key << ": " << value << "\n";
    }
}




/*
run:

Charlie: 36
Marley: 23

*/

 



answered Mar 22 by avibootz

Related questions

...