【问题标题】:Std Pair Initialization标准对初始化
【发布时间】:2012-12-29 18:58:56
【问题描述】:

这是我第一次与双人合作,完全困惑。 如何初始化一对以将其插入地图中?
我应该为此包含一些标准库吗?

#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.

 };  

【问题讨论】:

    标签: c++ standard-library std-pair


    【解决方案1】:

    你可以使用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));
    

    【讨论】:

      【解决方案2】:

      请改用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; 
          }
      
       }; 
      

      【讨论】:

      • 我是不是要疯了,还是因为insert 应该采用value_type 的单个参数(与键和值配对),所以这不起作用?没有 insert 接受键和值参数。
      • 这不起作用。它给出了以下错误:无法将参数 1 从 'std::pair<_ty1>' 转换为 'std::_Tree<_traits>::const_iterator' 在这种情况下我应该使用什么?
      • @sftrabbit 你是对的。有趣的是,我看的还不够。
      • @Ever 是的,我是这么认为的。它试图调用insert 的两个参数版本,它接受const_iterator 和一些值。
      • @Ever 看看我的编辑。您可以使用myMap[key] = value; 语法。就像其他答案一样。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2014-01-17
        • 2013-10-09
        • 2015-12-24
        • 2014-12-21
        • 2017-07-03
        • 1970-01-01
        • 2013-06-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多