如何声明和初始化此映射<pair <int,int>,bool>?

问题描述

当我尝试创建地图数据结构时,将设置为pair<pair<int,int>,bool,将 Value 设置为int

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

这是代码

#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时,会导致类似的构建错误

解决方法

您的示例中存在多个语法错误,并且由于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,true}); // Inserting

}