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>));
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.
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.
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.
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.
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();
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With