我正在使用 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/