Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an initializer_list on a map of vectors

Tags:

c++

c++11

stl

I've been trying to initialize a map of <ints, vector<ints> > using the new 0X standard, but I cannot seem to get the syntax correct. I'd like to make a map with a single entry with key:value = 1:<3,4>

#include <initializer_list>
#include <map>
#include <vector>
using namespace std;

map<int, vector<int> > A = {1,{3,4}};

....

It dies with the following error using gcc 4.4.3:

error: no matching function for call to std::map<int,std::vector<int,std::allocator<int> >,std::less<int>,std::allocator<std::pair<const int,std::vector<int,std::allocator<int> > > > >::map(<brace-enclosed initializer list>)

Edit

Following the suggestion by Cogwheel and adding the extra brace it now compiles with a warning that can be gotten rid of using the -fno-deduce-init-list flag. Is there any danger in doing so?

like image 483
Hooked Avatar asked May 17 '10 20:05

Hooked


People also ask

Can we use vector as a key in map?

In C++ we can use arrays or vector as a key against to a int value like: map<vector<int> ,int > m; Can I do same in MATLAB by containers.


1 Answers

As the comment above has mentioned, {1,{3,4}} is a single element in the map, where the key is 1 and the value is {3,4}. So, what you would need is { {1,{3,4}} }.

Simplifying the error:

error: no matching function for call to map<int,vector<int>>::map(<brace-enclosed initializer list>)

Not a precise error, but somewhat helpful nonetheless.

like image 115
Buğra Gedik Avatar answered Sep 27 '22 19:09

Buğra Gedik