This code moves one element from one unordered_map to another.

I would like to ask if my code below can be improved.

#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <unordered_map>

int main()
    struct Data
        int foo;
        bool boo;
    std::unordered_map<std::string, Data> map_A = {{"A", {1, true}}, {"B", {2, false}}};
    std::unordered_map<std::string, Data> map_B = {{"C", {3, false}}, {"D", {4, true}}};;

    std::string keyToMove = "C";
    map_A.insert({keyToMove, map_B[keyToMove]});

    std::cout << "map_A" << std::endl;
    auto it = map_A.begin();
    while(it != map_A.end())
        std::cout<<it->first<<" :: "<<it->second.foo<<std::endl;
    std::cout << "map_B" << std::endl;
    auto it2 = map_B.begin();
    while(it2 != map_B.end())
        std::cout<<it2->first<<" :: "<<it2->second.foo<<std::endl;
    return 0;


C :: 3
B :: 2
A :: 1
D :: 4
Program ended with exit code: 0
  • 2
    \$\begingroup\$ The word trying in the first sentence might indicate to some people on this site that the code isn't working. Since the results show that the code is working you might want to remove that word. \$\endgroup\$
    – pacmaninbw
    Jul 6, 2019 at 11:57
  • \$\begingroup\$ en.cppreference.com/w/cpp/container/unordered_map/extract \$\endgroup\$ Jul 6, 2019 at 16:22

1 Answer 1


Unused Includes
The code is not using std:vector, nor is it using anything from utilities. It might be better not to include these, that can improve your compile time and decrease the size of the generated code.

Don't Repeat Yourself
There are two obvious functions that can be written to shorten the code in main(). One function prints the contents of an unordered map and the other moves the contents from one map to the other. When you see code repeating itself in a function that is a good indication that you can create a function to reduce the amount of code in the function to make it simpler.

Program Exit Status
In this particular program it isn't necessary to have return 0; in main() C++ will generate it for you. When you have programs that might fail it might be better to include cstdlib and use the symbolic constants EXIT_SUCCESS and EXIT_FAILURE to indicate success or failure to the calling program.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.