c++ map vector as keys

To use a vector as keys in a C++ map, follow these steps:

  1. Include the necessary header files:
  2. #include <iostream> for input/output operations.
  3. #include <map> for using the map container.
  4. #include <vector> for using the vector container.

  5. Declare the map variable with the vector as the key type:

  6. std::map<std::vector<int>, int> myMap;
  7. This declares a map called myMap, where the keys are vectors of integers and the values are integers.

  8. Create a vector and assign it values:

  9. std::vector<int> myVector = {1, 2, 3};
  10. This creates a vector called myVector and assigns it the values 1, 2, and 3.

  11. Insert the vector and its corresponding value into the map:

  12. myMap.insert(std::make_pair(myVector, 10));
  13. This inserts the key-value pair into the map. In this example, the vector myVector is the key, and the value associated with it is 10.

  14. Access the value using a vector key:

  15. int value = myMap[myVector];
  16. This retrieves the value associated with the vector key myVector from the map and assigns it to the variable value.

  17. Update the value associated with a vector key:

  18. myMap[myVector] = 20;
  19. This updates the value associated with the vector key myVector to 20 in the map.

  20. Check if a vector key exists in the map:

  21. if (myMap.count(myVector) > 0) { ... }
  22. This checks if the vector key myVector exists in the map. If it does, the code inside the if statement will be executed.

  23. Remove a vector key and its corresponding value from the map:

  24. myMap.erase(myVector);
  25. This removes the vector key myVector and its associated value from the map.

Remember to adapt the code according to your specific needs and modify the vector and map types as required.