RockAndaHardPlace
RockAndaHardPlace

Reputation: 417

c++ - Inserting 3 variable values into a multimap

I'm new to the use of maps and multimaps, and I'm having trouble (compiler errors and warnings) when trying to insert 3 values into a multimap via the use of a pair of strings (acting as the key) and an int value:

This is my multimap declaration:

multimap<pair<string, string>, int> wordpairs;

This is how I'm trying to populate the multimap:

int toInsert = 0;

  for (int i = 0; i < s; i++) {

    wordpairs.insert((words[i], words[i+1]), toInsert);

  }

where words is:

vector<string> words

I'm getting this error and a bunch of warnings:

error: no matching function for call to ‘std::multimap<std::pair<std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >, int>::insert(std::__cxx11::basic_string<char>&, int&)’
     wordpairs.insert((words[i], words[i+1]), toInsert);
                                                      ^

Not sure how to properly insert the values I want to. :(

Upvotes: 1

Views: 2044

Answers (3)

Captain Giraffe
Captain Giraffe

Reputation: 14705

The insert member function only expects one argument.

wordpairs.insert((words[i], words[i+1]), toInsert);

provides at least two. It is not valid grammar (I think, the comma operator may or may not be valid in this context.).

The insert is expecting a pair, {key, value}, Your key is a pair {words[i], words[i+1]} combined this yields with the magic of uniform initialization:

    wordpairs.insert({{words[i], words[i+1]}, toInsert});

This requires C++11.

Additional reading as to why this works is found in a very popular softwareengineering question.

Upvotes: 1

RyanP
RyanP

Reputation: 1918

Your key is a pair (pair<string, string>) and (words[i], words[i+j]) is not a pair. You'll need wordpairs.emplace(std::make_pair(words[i], words[i+j]), toInsert)

Edit: There are two ways to put something into a map (or multimap). The first is insert in which it needs an object to copy into your map. Your map contains a pair of < pair< string,string >, int >. So you could call insert like... wordpairs.insert(std::make_pair(std::make_pair(words[i], words[i+j]), toInsert)) OR you can emplace them. Emplace constructs the object in place, so instead of constructing it with make_pair and then copying it into the map, you can just construct it in place with the given call.

Upvotes: 1

ayushkum36
ayushkum36

Reputation: 59

You should use this wordpairs.insert( make_pair(make_pair(words[i], words[i+1]), toInsert));

Upvotes: 0

Related Questions