【问题标题】:How do I declare and initialize this map<pair<int, int>, bool>?如何声明和初始化这个 map<pair<int, int>, bool>?
【发布时间】:2021-01-17 23:17:57
【问题描述】:

虽然我正在尝试创建一个地图数据结构,其中 Keypair&lt;pair&lt;int, int&gt;, boolValueint

  • 在 xcode 上编译时,构建失败并出现链接器错误
  • 在 cpp.sh 或 godbolt.org 等网站上编译时,它 引发模板参数错误

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <utility>
using namespace std;

typedef std::pair<int,int> pair;

struct comp
{
    template<typename T>
    bool operator()(const T &l, const T &r) const
    {
        if (l.first == r.first)
            return l.second > r.second;

        return l.first < r.first;
    }
};

int main()
{
    
    map<pair,bool,comp> mp = 
    {
        {std::make_pair<4,0>,true},
        {std::make_pair<4,1>,true}
    }; //Initializing

    mp.insert(make_pair(3,0),true); //Inserting

    return 0; 
}

我使用模板编写 comp 结构的原因是用于密钥 ordering
但是,从技术上讲,我不需要为我正在解决的问题订购。
因此,当我尝试使用unordered_map 时,会导致类似的构建错误

【问题讨论】:

  • 您应该在问题中逐字包含错误消息。话虽如此,将pair 用作std::pair&lt;int,int&gt; 的别名并结合using namespace std; 似乎不是一个好主意。
  • make_pair 调用中用括号替换尖括号。 std::pair 是可比的,所以你的 comp 是多余的。
  • @bipll:你说得对,我删除了comp,它成功了,谢谢。如果我的密钥是 ,则可能需要 comp

标签: c++ dictionary data-structures stl


【解决方案1】:

您的示例中有几个语法错误,并且由于using namespace std; 在全局命名空间中使用冲突名称 (pair) 定义别名时出现歧义。

以下是您的代码示例:

#include <map>
#include <utility>

typedef std::pair<int, int> Pair;

struct comp {
  template <typename T> bool operator()(const T &l, const T &r) const {
    if (l.first == r.first)
      return l.second > r.second;

    return l.first < r.first;
  }
};

int main() {

  std::map<Pair, bool, comp> mp = {
      {std::make_pair(4, 0), true},
      {std::make_pair(4, 1), true}}; // Initializing

  mp.insert({std::make_pair(3, 0), true}); // Inserting

}

【讨论】:

  • 谢谢你,我无法相信 xcode 没有为make_pair 使用尖括号并为insert 缺少花括号而引发更具描述性的错误
  • @PersistentCache 我们根本无法读取错误消息,因为您没有告诉使用它是什么;)。也许很难破译,但通常错误消息确实包含很多信息,甚至经常建议修复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 2014-03-03
  • 2021-11-18
  • 2010-11-20
  • 1970-01-01
  • 2010-09-13
相关资源
最近更新 更多