我有一个具有唯一键的结构.我想将这些结构的实例插入到集合中.我知道要做到这一点,<运算符必须重载,以便set可以进行比较以进行插入.
以下不起作用:
#include <iostream>
#include <set>
using namespace std;
struct foo
{
int key;
};
bool operator<(const foo& lhs, const foo& rhs)
{
return lhs.key < rhs.key;
}
set<foo> bar;
int main()
{
foo *test = new foo;
test->key = 0;
bar.insert(test);
}
Run Code Online (Sandbox Code Playgroud) 我使用一个集来保存包含几个字符串的结构.我希望能够使用集合的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 …Run Code Online (Sandbox Code Playgroud)