我如何声明和初始化这个 map<pair<int, int>, bool>?

Ele*_*nts 0 c++ dictionary stl data-structures

当我尝试使用Key aspair<pair<int, int>, boolValue as创建地图数据结构时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; 
}

Run Code Online (Sandbox Code Playgroud)

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

asm*_*mmo 5

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

}
Run Code Online (Sandbox Code Playgroud)