How to convert map values to a list in C++

1 Answer

0 votes
#include <iostream>
#include <map>
#include <list>

// Function to extract map values into a list
std::list<int> mapValuesToList(const std::map<std::string, int>& myMap) {
    std::list<int> valueList;

    // Iterate over the map and add values to the list
    for (const auto& pair : myMap) {
        valueList.push_back(pair.second);
    }

    return valueList;
}

int main() {
    std::map<std::string, int> myMap = {
        {"Red", 30},
        {"Green", 57},
        {"Blue", 86},
        {"Yellow", 102}
    };

    // Convert map values to a list
    std::list<int> values = mapValuesToList(myMap);

    // Print the list
    std::cout << "Values in the list: ";
    for (int value : values) {
        std::cout << value << " ";
    }
}



/*
run:

Values in the list: 86 57 30 102 

*/

 



answered Aug 23, 2025 by avibootz

Related questions

2 answers 185 views
1 answer 46 views
1 answer 81 views
1 answer 72 views
1 answer 92 views
...