STD对初始化

Std Pair Initialization

本文关键字:初始化 STD      更新时间:2023-10-16

这是我第一次使用对,完全困惑。如何初始化一对以将其插入地图?
我应该为此提供一些标准库吗?

#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方法可以节省您必须命名sd的类型。

请注意,此处适当的功能是operator[],而不是insertstd::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));

而不是使用std::make_pair。喜欢:

#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; 
    }
 }; 

对于map<K, T>value_type实际上是pair<K const, T>。但是,最简单的访问方法是使用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));

在C 11中,您可以使用更轻松的emplace接口:

Road_map.emplace(map_type::key_type(s, d), b);