简体   繁体   中英

unordered_map insert() error

I can compile this code that I got from an MSDN page :

using namespace std
typedef std::unordered_map<char, int> Mymap; 
Mymap c1;

c1.insert(Mymap::value_type('a', 1)); 
c1.insert(Mymap::value_type('b', 2)); 
c1.insert(Mymap::value_type('c', 3)); 

But when I change it to be:

using namespace std
typedef std::unordered_map<int, vector<int> > Mymap;
Mymap c1;

c1.insert(Mymap::value_type(1, vector<int> v (1,1))); 
c1.insert(Mymap::value_type(2, vector<int> v (1,2))); 
c1.insert(Mymap::value_type(3, vector<int> v (1,3))); 

I get the errors (the line numbers are obviously off for the snippet):

myfile.cpp:121:29: error: expected primary-expression before ‘(’ token
myfile.cpp:121:45: error: expected primary-expression before ‘v’
myfile.cpp:122:32: error: expected primary-expression before ‘(’ token
myfile.cpp:122:48: error: expected primary-expression before ‘v’
myfile.cpp:123:32: error: expected primary-expression before ‘(’ token
myfile.cpp:123:48: error: expected primary-expression before ‘v’

The hash map should be "int => list of ints". With the list being initialized with one number.

What is the problem here? Do I need to use something other than value_type ?

c1.insert(Mymap::value_type(1, vector<int> v (1,1))); 
                                           ^ // What's this 'v' doing there?

What you are looking for is:

    c1.insert(Mymap::value_type(1, vector<int>(1,1)));

That is, no v . vector<int> v(1, 1); declares a variable of type vector<int> , but you aren't attempting to declare a variable, you're attempting to construct a temporary object, for which no name is required (or allowed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM