Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map of vectors in STL?

Tags:

c++

stl

I want to have a map of vectors, (but I don't want to use pointer for the internal vector), is it possible?

// define my map of vector map<int, vector<MyClass> > map;  // insert an empty vector for key 10. # Compile Error map.insert(pair<int, vector<MyClass> >(10, vector<MyClass>));  

I know that if I have used pointer for vector, as follows, it would be fine, but I wonder if I can avoid using pointer and use the above data structure (I don't want to manually delete)

// define my map of vector map<int, vector<MyClass>* > map;  // insert an empty vector for key 10. map.insert(pair<int, vector<MyClass>* >(10, new vector<MyClass>));  
like image 622
chen Avatar asked Sep 04 '09 17:09

chen


People also ask

Can we make map of vector?

Map of Vectors in STL: Map of Vectors can be very efficient in designing complex data structures. Syntax: map<key, vector<datatype>> map_of_vector; OR map<vector<datatype>, key> map_of_vector; For example: Consider a simple problem where we have to check if a vector is visited or not.

How do I insert a map in STL?

map::insert() function is an inbuilt function in C++ STL, which is defined in header file. insert() is used to insert new values to the map container and increases the size of container by the number of elements inserted.

What is an STL map?

​Maps are a part of the C++ STL. Maps are associative containers that store elements in a combination of key values and mapped values that follow a specific order. No two mapped values can have the same key values. In C++, maps store the key values in ascending order by default. A visual representation of a C++ map.

Can we use vector in Unordered_map?

unordered_map uses vector as the key You can use the following method if you'd like to make the best of STL. }; Note that you can use any kind of operation to generate a hash. You just need to be creative so that collisions are minimized.


2 Answers

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(); 
like image 73
fbrereto Avatar answered Oct 03 '22 00:10

fbrereto


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 ;-)

like image 25
Steve Jessop Avatar answered Oct 03 '22 00:10

Steve Jessop