这是我第一次结对工作,完全一头雾水。
如何初始化一对插入到map中?
我应该为此包含一些标准库吗?
#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.
};
最佳答案
你可以使用std::make_pair
:
Road_map[make_pair(s, d)] = b;
或者,您可以像这样构造一个std::pair
:
Road_map[pair<string,string>(s,d)] = b;
std::make_pair
方法使您不必命名 s
和 d
的类型。
请注意,此处合适的函数是 operator[]
而不是 insert
。 std::map::insert
接受一个参数,它是一个 std::pair
包含您要插入的键和值。你必须这样做:
Road_map.insert(pair<const pair<string,string>, int>(make_pair(s, d), b);
你可以用 typedef
让它更漂亮一点:
typedef map<pair<string,string>, int> map_type;
Road_map.insert(map_type::value_type(map_type::key_type(s, d), b));
关于c++ - 标准对初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14084919/