質問

I have the following code:

#include <iostream>
#include <utility>
#include <map>

using namespace std;

int main()
{
map<int, map<string, int> > mapa;

// way A
mapa[10]["aaa"] = 20;

// way B -> Compilation Error
pair<int, pair<string, int> > par(10, make_pair("aaa", 20));
mapa.insert(par);


return 0;
}

I know that "way A" of populating the map works. I want to use "way B" but it throw a compilation Error: error: no matching function for call to ‘std::map, int>::map(const std::pair, int>&)’

How can I populate the nested map with insert operator.

Pd: I don't use [] operator because it requires the default constructor to be defined which I don't have since I am using time_period objects from Boost.

役に立ちましたか?

解決

Well the type of your map is map of (int -> map of (string -> int)) but you are trying to insert an entry of type map of (int -> pair (string, int)). A pair is not a map, thus the error.

EDIT:

According to the documentation, a call to map's [] operator is equivalent to a series of other operations:

mapped_type& operator[] (const key_type& k);

A call to this function is equivalent to:
(*((this->insert(make_pair(k,mapped_type()))).first)).second

so in your case, the call mapa[10]["aaa"] = 20; is equivalent to:

(*(( (*((mapa.insert(make_pair(10,map<string, int>()))).first)).second
  .insert(make_pair("aaa",20))).first)).second

but I believe if either key 10 or aaa exist, no element will be inserted in the map. I suggest you read the docs thoroughly and test for the expected behavior.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top