0

So I've created

 map<string, vector<int>> mylist;

but I'm having trouble adding items to it. I tried creating a vector and then inserting a string and the vector in the map, but visual studio is giving me an error on the line with the insert function (It says no instance of overloaded function matches the argument list). This is what I'm doing:

vector<int> variable_list(some_integer);
mylist.insert(string_variable, variable_list);

How should I be adding the vector to the map? Can I create the vector in the insert function somehow?

Also, I'll be initializing the vector with one int, but then I'll want to go back and add more later. How do I access a vector within a map?

Thanks for your help.

Michael
  • 356
  • 2
  • 4
  • 12
  • Can you copy paste the precise error message please ? – hivert Feb 05 '14 at 17:44
  • 1
    See this question on how to insert to a map: http://stackoverflow.com/questions/4286670/how-do-i-insert-into-a-map – Csq Feb 05 '14 at 17:45
  • You can just do `my_map[key].push_back(value)`. If the `key` doesn't exist, it's created. – Det Feb 21 '20 at 23:00

3 Answers3

4

For this kind of question, I would recommend looking up a good reference, such as cppreference.com.

If you go there and you look up std::map::insert, you will see overload with this signature: std::pair<iterator,bool> insert( const value_type& value );, which tells us that it expects something called value_type. If you then look at std::map, you will see that value_type is typedef for std::pair<const Key, T>.

Now you can use std::make_pair to create the proper type, like this: mylist.insert(std::make_pair<const string, vector<int>).


As a side note, I have to strongly recommend finding an introductionary book/something, because the rest of your question suggests that you are rather confused about more than just inserting into map.
For starters, vector<int> variable_list(number) will not construct a vector with number in it, but will construct a vector of number zeroes.

Xarn
  • 3,460
  • 1
  • 21
  • 43
2

You need to call mylist.insert(std::make_pair(string_variable, variable_list));. You are looking for the version of std::map::insert that takes the value_type as its argument, which, in your case, is std::pair<std::string, std::vector<int>>.

Kristian Duske
  • 1,769
  • 9
  • 14
2

map::insert takes a std::pair. You can either use make_pair or write mylist[string_variable] = variable_list;

MooseBoys
  • 6,641
  • 1
  • 19
  • 43