容器如何std::set<T>检查两个对象是否唯一?我尝试覆盖相等运算符(==),但它不起作用。
我想这样做的原因是,我有一个类 Person,并且我指定我的 Person 是同一个人,如果他们具有相同的名字(甚至可能是生日、地址等)。
在ccpreference.com中,他们写了以下内容(我有点不清楚):
在标准库使用比较概念的地方,唯一性 是通过使用等价关系来确定的。不精确地说,如果两个对象 a 和 b 的比较结果都不小于另一个,则认为两个对象 a 和 b 是等价的(不是唯一的): !comp(a, b) && !comp(b, a)。
我认为这个问题也扩展到其他 STL 容器甚至算法(甚至可能扩展到整个 STL)。因此,如果将来我想使用该函数std::find,我将查找人名而不是对象本身。它是否正确?
我想添加一些示例代码。
// My operator overloading comparing two strings.
bool operator==(Node & rhs) const {
return this->name.compare(rhs.name);
}
Run Code Online (Sandbox Code Playgroud)
然后,在 UnitTest 中,我将同名的对象两次添加到集合中。它被添加两次(但根据operator==.
void test_adding_two_identical_nodes() {
// The pool is a set<Node> inside
model::Node_Pool pool{};
pool.store_node(model::Node{"Peter"});
pool.store_node(model::Node{"Peter"});
// Should be only 1 because the same node should be added once into a set.
ASSERT_EQUAL(1, pool.size());
}
Run Code Online (Sandbox Code Playgroud)
std::set<T>不比较使用==. 默认情况下,它使用 进行比较std::less<T>。std::less<T>默认情况下,依次使用运算符<。
实现集合的一种方法是重写operator<,如下所示:
#include <set>
#include <cassert>
struct Person {
const char *name;
int uid;
};
bool operator<(const Person& a, const Person& b) {
return a.uid < b.uid;
}
int main () {
Person joe = {"joseph", 1};
Person bob = {"robert", 2};
Person rob = {"robert", 3};
Person sue = {"susan", 4};
std::set<Person> people;
people.insert(joe);
people.insert(bob);
people.insert(rob);
assert(people.count(joe) == 1);
assert(people.count(bob) == 1);
assert(people.count(rob) == 1);
assert(people.count(sue) == 0);
Person anonymous_3 = {"", 3};
assert( std::strcmp(people.find(anonymous_3)->name, "robert") == 0);
}
Run Code Online (Sandbox Code Playgroud)
或者,可以在声明 时将比较运算符作为模板参数传递set。在上面的示例中,这可能是比较运算符:
struct Person_Compare {
bool operator()(const Person& a, const Person& b) const {
return a.uid < b.uid;
}
};
Run Code Online (Sandbox Code Playgroud)
声明std::set可能如下所示:
std::set<Person, Person_Compare> people;
Run Code Online (Sandbox Code Playgroud)
该示例的其余部分保持不变。