c++ - 在 std::set 中查找对象时出错

标签 c++ c++11

我正在尝试使用 find() 方法在集合中查找对象。但是,我无法做到这一点,似乎我发送了错误的 key 。什么是正确的做法?

#include <iostream>
#include <set>
#include <utility>

struct Class {
  std::pair<int,int> data;
  int val = 0;
  int id = 0; ///ID for the object

};

struct CompClass {
      bool operator() (const Class& lhs, const Class& rhs) const
  {
    if (lhs.data.first == rhs.data.first) return lhs.data.second < rhs.data.second;

    return lhs.data.first<rhs.data.first;
    }
    };

int main ()
{

  Class c1,c2,c3,c4;


  c1.val = 92;c1.id = 2; c1.data = std::make_pair(92,2);
  c2.val = 94;c2.id = 3; c2.data = std::make_pair(94,3);
  c3.val = 92;c3.id = 1; c3.data = std::make_pair(10,1);

  std::set<Class,CompClass> fifth;                 // class as Compare

    fifth.insert(c1);fifth.insert(c2);fifth.insert(c3);

    for (auto x: fifth) {std::cout << x.id << "  " << x.val << std::endl;} 

    if (fifth.find(  std::make_pair(92,2)  ) != fifth.end() ) {std::cout << "Got it";} //Error

  return 0;
}

最佳答案

std::set<T>::find 采用 T 类型的参数在 C++11 中。您需要提供一个 Class对象,不是 std::pair :

if (fifth.find(  Class{92,2,0,0}  ) != fifth.end() ) {std::cout << "Got it";}

关于c++ - 在 std::set 中查找对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35586734/

相关文章:

c++ - 依赖类型 : Template argument deduction failed

c++ - c++ 中 map_instance[key] 与 map_instance.find(key) 的区别

c++ - std::static_pointer_cast 与 static_cast<std::shared_ptr<A>>

c++ - 在同一进程中使用的两个模块中使用同步对象的通用名称是否安全?

c++ - 使用 boost::algorithm::split_regex 拆分字符串

c++ - 来自 Lambda 的访问冲突偶尔会出现

c++ - 激活上下文导致动态加载的 DLL 上的文件句柄泄漏

c++ - 如何从 QGraphicsView 中检索选定区域?

c++ - 用户自定义文字串 : compile-time length check

c++ - 虚拟析构函数用例