map of vectors in STL?

The first data structure will work. You might want to typedef some of the code to make future work easier:

typedef std::vector<MyClass>      MyClassSet;
typedef std::map<int, MyClassSet> MyClassSetMap;

MyClassSetMap map;
map.insert(MyClassSetMap::value_type(10, MyClassSet()));

or (thanks quamrana):

map[10] = MyClassSet();

You could use the [] operator.

It will insert the value into the map:

map[10]; // create the 10 element if it does not exist
         // using the default constructor.

If you are going to use the value soon after construction then:

std::vector<MyClass>&  v = map[10];

Now it's constructed and you have a local reference to the object.


Yes, but your second line should be:

map.insert(pair<int, vector<MyClass> >(10, vector<MyClass>()));

This inserts a pair consisting of the integer 10, and an empty vector. Both will be copied, and if you're dealing with large vectors then you'll want to be careful about copies.

Also: don't call variables "map" while using namespace std. You're scaring me ;-)

Tags:

C++

Stl