c++ - 如何使 find() 与一组结构一起工作?

标签 c++ struct set find containers

我正在使用 set 来保存包含多个字符串的结构。我希望能够使用集合的 find() 功能。但是,由于该集合包含结构,因此它不起作用。我希望 find() 只查看结构中的一个字符串。如何做到这一点?

这是我尝试使用的代码。它工作正常,除了使用 find() 的部分:

#include <iostream>
#include <string>
#include <set>
using namespace std;

struct test
{
    string key;
    string data;
};

bool operator<(const test & l, const test & r)
{
    return l.key < r.key;
}

bool operator==(const test & l, const test & r)
{
    return l.key == r.key;
}

set<test> s;

int main()
{
    test newmember;
    newmember.key = "key";
    newmember.data = "data";
    s.insert(newmember);
    s.find("key");
}

以下是我尝试编译它时收到的错误消息:

test.cpp:30:7: error: no matching member function for call to 'find'
    s.find("key");
    ~~^~~~
In file included from test.cpp:3:
In file included from /usr/include/c++/4.2.1/set:65:
/usr/include/c++/4.2.1/bits/stl_set.h:429:7: note: candidate function not viable: no known conversion from 'const char [4]' to 'const key_type' (aka 'const test') for 1st argument
      find(const key_type& __x)
      ^
/usr/include/c++/4.2.1/bits/stl_set.h:433:7: note: candidate function not viable: no known conversion from 'const char [4]' to 'const key_type' (aka 'const test') for 1st argument
      find(const key_type& __x) const
      ^
1 error generated.

最佳答案

我建议你operator<operator==到您的结构而不是重载全局运算符,我发现它更干净;示例:

struct test
{
  string key;
  string data;

  bool operator<(const test& rhs) const
  {
    return key < rhs.key;
  }

  bool operator==(const test& rhs) const
  {
    return key == rhs.key;
  }
};

现在开始您的真正问题 - 您正在将字符串传递给 find()函数,但它只接受 test 类型的结构.为此,添加一个用于自动转换的构造函数,因此最终结构将如下所示:

struct test
{      
  string key;
  string data;

  test(const std::string& strKey = "", const std::string& strData = "")
  : key(strKey),
    data(strData) {}

  bool operator<(const test& rhs) const
  {
    return key < rhs.key;
  }

  bool operator==(const test& rhs) const
  {
    return key == rhs.key;
  }
};

然后传递一个字符串给find()会自动调用构造函数并创建一个临时的 test仅包含相关键的结构。请注意,在这种特殊情况下,不得声明构造函数 explicit .

关于c++ - 如何使 find() 与一组结构一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5865303/

相关文章:

c - linux内核中红黑节点的struct对齐

algorithm - 在 3D 中搜索点之间的 K 个最小距离

java - 生成 5 个随机字符串并将它们添加到 Java 中的 Set

algorithm - 这个问题是 NP 问题吗,它有名字吗?

c++ - 矩阵中的嵌套 while 循环

c++ - 在 C++ 命令行中获取参数

swift - 如何获取指向 Swift 结构的 C 指针的值?

C++ 获得足够的权限以绑定(bind)到端口 80

c++ - 尝试翻译混合模式的公式

c - 如何在C中访问结构数组内的结构成员