Reputation: 1689
This is my first time working with pairs, totally confused.
How to initialize a pair as to insert it in the map?
Should I include some standard library for this?
#include <string>
#include <map>
using namespace std;
class Roads
{
public:
map< pair<string,string>, int > Road_map;
void AddRoad( string s, string d )
{ int b = 2 ; Road_map.insert( pair<s,d>, b) ; } //pair<s,d> is wrong here.
};
Upvotes: 2
Views: 12273
Reputation: 21317
Use std::make_pair
instead. Like so:
#include <string>
using namespace std;
class Roads
{
public:
map< pair<string,string>, int > Road_map;
void AddRoad( string s, string d )
{
int b = 2 ;
Road_map[make_pair(s,d)] = b;
}
};
Upvotes: 3
Reputation: 110658
You can use std::make_pair
:
Road_map[make_pair(s, d)] = b;
Alternatively, you can construct an std::pair
like so:
Road_map[pair<string,string>(s,d)] = b;
The std::make_pair
approach saves you having to name the types of s
and d
.
Notice that the appropriate function here is operator[]
and not insert
. std::map::insert
takes a single argument which is a std::pair
containing the key and value you want to insert. You would have to do that like this:
Road_map.insert(pair<const pair<string,string>, int>(make_pair(s, d), b);
You can make this a bit prettier with typedef
:
typedef map<pair<string,string>, int> map_type;
Road_map.insert(map_type::value_type(map_type::key_type(s, d), b));
Upvotes: 4
Reputation: 477010
For a map<K, T>
, the value_type
is actually pair<K const, T>
. However, the easiest way to access this is by using typedefs:
typedef std::pair<std::string, std::string> string_pair;
typedef std::map<string_pair, int> map_type;
// ...
Road_map.insert(map_type::value_type(map_type::key_type(s, d), b));
In C++11 you can use the easier emplace
interface:
Road_map.emplace(map_type::key_type(s, d), b);
Upvotes: 1