我正在使用一个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<
and 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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)