How to combine 2 maps into a third map in C++

1 Answer

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

int main() {
    std::map<int, std::string> map1 = {{1, "aaa"}, {2, "bbb"}};
    std::map<int, std::string> map2 = {{3, "ccc"}, {4, "ddd"}, {2, "XYZ"}};

    std::map<int, std::string> combined;

    // Insert elements from map1
    combined.insert(map1.begin(), map1.end());

    // Insert elements from map2
    combined.insert(map2.begin(), map2.end());

    // Print combined map
    for (const auto& [key, value] : combined) {
        std::cout << key << ": " << value << '\n';
    }
}



/*
run:

1: aaa
2: bbb
3: ccc
4: ddd

*/

 



answered Aug 25, 2025 by avibootz

Related questions

2 answers 104 views
2 answers 83 views
3 answers 92 views
2 answers 101 views
1 answer 72 views
...