c++ - Error when using vectors in a map -


i attempting add vector position in map according key.

vector<string> words; map<string, vector<string>> wordmap;  (int = 0; < words.size(); i++) {     string word = words.at(i);      if (wordmap.find(word) == wordmap.end())         wordmap.insert(make_pair(word, vector<string>()));      vector<string> context = { "empty" };      if (i == 0)         context = { "beginning of words", words[i + 1], words[i + 2] };     else if(i == 1)         context = { "beginning of words", words[i - 1], words[i + 1], words[i + 2] };     else if (i == words.size() - 2)         context = { words[i - 2], words[i - 1], words[i + 1], "end of words" };     else if(i == words.size() - 1)         context = { words[i - 2], words[i - 1], "end of words" };     else         context = { words[i - 2], words[i - 1], words[i + 1], words[i + 2] };      wordmap[word].push_back(context);     cout << context[0] << endl; } 

i keep getting following error @ period in

wordmap[word].push_back(context);  error: no instance of overloaded function "std::vector<_ty,_alloc>::push_back[with_ty=std::string,_alloc=std::allocator<std::string>]" matches argument list  argument types are: (std::vector<std::string, std::allocator<std::string>>)  object type std::vector<std::string, std::allocator<std::string>> 

everything else in program works , can post if need me to, error when try use push_back. need use push_back because cannot reassign value. have keep previous values located @ key, push_back ideal. appreciated.

instead of:

wordmap[word].push_back(context); 

you should append new vector:

std::copy(context.begin(), context.end(), std::back_inserter(wordmap[word])); 

another thing dont need initialization:

if (wordmap.find(word) == wordmap.end())         wordmap.insert(make_pair(word, vector<string>())); 

as later on wordmap[word] add value initialized element.

when operator[] called on map instance if no value present @ given key, new element added, reference returned.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -