c++ - 在包含自定义类型的集合中查找

标签 c++ set

我有一个存储自定义数据的集合,我想按键值搜索它。

这是一个简单的例子:

struct Data {
  Data(int x, int y):x(x), y(y){}
  int x;
  int y;
};

struct Compare {
  bool operator() (const Data& lhs, const Data& rhs) {
    return lhs.x < rhs.x;
  }
};

int main()
{
  set<Data, Compare> s;
  s.insert(Data(2, 77));
  s.insert(Data(3, 15));
  s.insert(Data(1, 36));
  for (auto i:s)
    cout<<i.x<<" "<<i.y<<endl;

  auto i = s.find(3);  // <-- Not working
  auto i = s.find(Node(3, 0));
  if (i != s.end())
    cout<<"found"<<endl;
  else
    cout<<"not found"<<endl;
}

此集合仅按 x 排序,但我必须创建一个临时对象以在集合中搜索:s.find(Node(3, 0))

是否可以只按键搜索?即 s.find(3)?

最佳答案

在c++14中,你可以使用is_transparent :

Finds an element with key that compares equivalent to the value x. This overload only participates in overload resolution if the qualified-id Compare::is_transparent is valid and denotes a type. It allows calling this function without constructing an instance of Key

struct Compare {
  using is_transparent = std::true_type;
  bool operator() (const Data& lhs, const Data& rhs) const {
    return lhs.x < rhs.x;
  }
  bool operator() (const Data& lhs, const int & rhsx) const {
    return lhs.x < rhsx;
  }
  bool operator() (const int & lhsx, const Data& rhs) const {
    return lhsx < rhs.x;
  }
};

现在您的代码是 valid .

关于c++ - 在包含自定义类型的集合中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32653771/

相关文章:

c++ - 为什么这段代码不能正确读取用户输入?

c++ - gets() 正式弃用了吗?

c++ - 在 C++ 中,首先发生的是返回对象的拷贝还是本地对象的析构函数?

c++ set 输出的元素比它包含的元素多得多

c++ - 插入 STL 集中

c++ - 在 C++ 复杂性和实现中选择位 vector

c++ - 没有 getline 的重载函数实例

ios - 通过 GitHub 或其他一般 : How to remove the sign-on info from settings or general in Xcode iOS app - 共享源代码

python - 我不明白这个KeyError?

java - 如何组合这些 Set<?为我的 API 扩展 Vector> 过滤函数?