cateof cateof - 1 year ago 98
C++ Question

Extract vector from std::map<int, std::vector>

Here is my code

#include <iostream>
#include <map>
#include <string>
#include <vector>

typedef std::vector<int> VectorInt;
typedef std::map<int, VectorInt> MapVectorInt;

int main() {
MapVectorInt myMap;

VectorInt v1;

VectorInt v2;

myMap.insert(std::make_pair(0, v1));
myMap.insert(std::make_pair(1, v2));

return 0;

What is the bese way to take (extract/get) the vector at position x (eg 1,2...);

Answer Source

You can refer to the vector in the map with myMap[0] or myMap[1].

You could make an alias for either of those, e.g. auto& x = myMap[0];. Using the alias will access the vector as it is stored in the map.

To take a copy of the vector (so that you can modify the map contents without changing the copy), it is just the same as copying any other object:

auto x = myMap[0];

Note that 0 and 1 refer to the key you used in the insert call; not to the search order or the insertion order (although in your example those things all happen to be the same).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download