3
\$\begingroup\$

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]});
 map_B.erase(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;
 it++;
 }
 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;
 it2++;
 }
 return 0;
}

Result:

map_A
C :: 3
B :: 2
A :: 1
map_B
D :: 4
Program ended with exit code: 0
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jul 6, 2019 at 5:55
\$\endgroup\$
2
  • 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\$ Commented Jul 6, 2019 at 11:57
  • \$\begingroup\$ en.cppreference.com/w/cpp/container/unordered_map/extract \$\endgroup\$ Commented Jul 6, 2019 at 16:22

1 Answer 1

2
\$\begingroup\$

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.

answered Jul 6, 2019 at 12:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.