How to have a set of structs in C++
问题 I have a struct which has a unique key. I want to insert instances of these structs into a set. I know that to do this the < operator has to be overloaded so that set can make a comparison in order to do the insertion. The following does not work: #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); } 回答1: