使用一组结构查找工作

nod*_*nja 7 c++ containers struct set find

我使用一个集来保存包含几个字符串的结构.我希望能够使用集合的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");
}
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

Mep*_*ane 12

我建议你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;
  }
};
Run Code Online (Sandbox Code Playgroud)

现在问你真正的问题 - 你正在将一个字符串传递给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;
  }
};
Run Code Online (Sandbox Code Playgroud)

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


bed*_*uin 3

为了能够将您的结构放入set您必须指定operator<您的结构。您可以operator<通过比较相应的字符串成员来得出返回结果。

为了能够使用,find您可以指定您的结构在相应的字符串成员相等时operator==返回。true

样本:

    // code from your question used here

    int main()

{
    test newmember;
    newmember.key = "key";
    newmember.data = "data";

    test findMember;
    findMember.key = "key";
    // as operator== and operator< doesn't care about data field we can left it be
    // initialized by default constructor

    s.insert(newmember);
    s.find(findMember);
}
Run Code Online (Sandbox Code Playgroud)

如果您想使用find()参数进行调用,您可以为您的结构string提供隐式构造函数,例如如下所示:stringtest

struct test {
//...
  test(const string &in_key) : key(in_key) {}
//...
};
Run Code Online (Sandbox Code Playgroud)

但是使用隐式构造函数并不是一个好的技术,因为它可能会导致代码中更远的地方发生一些不可预测的转换。