Std Pair Initialization
Solution 1
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));
Solution 2
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;
}
};
Solution 3
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);
Fatima
Updated on June 04, 2022Comments
-
Fatima about 2 years
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. };
-
Joseph Mansfield over 11 yearsAm I going crazy or will this not work because
insert
is supposed to take a single argument ofvalue_type
(pair with key and value)? There's noinsert
that takes key and value arguments. -
Fatima over 11 yearsThis didn't work. It gave the following error: cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'std::_Tree<_Traits>::const_iterator' What should I use in this case ?
-
Rapptz over 11 years@sftrabbit you are correct. Interestingly enough I didn't look at it enough.
-
Joseph Mansfield over 11 years@Ever Yeah, I thought so. It's trying to call the two argument version of
insert
which takes aconst_iterator
and some value. -
Fatima over 11 years@sftrabbit Okay, what should I use in this case ? Is there an alternative for insert?
-
Rapptz over 11 years@Ever look at my edit. You can use
myMap[key] = value;
syntax. Just like other answers have provided.