std::set with user defined type, how to ensure no duplicates(std::set 与用户定义的类型,如何确保没有重复)
问题描述
所以我有一个 std::set 需要保持特定的顺序以及不允许重复用户定义的(由我)类型.现在我可以通过重载'<'来让订单正常工作我的类型中的运算符.但是,该集合没有适当地检测到重复项,老实说,我不完全确定它是如何在内部执行此操作的.我已经重载了'=='运算符,但不知何故我不确定这是该集合实际使用的内容吗?所以问题是当您添加值时,集合如何确定重复项?以下是相关代码:
So I have an std::set which needs to keep specific ordering as well as not allowing duplicates of a user defined (by me) type. Now I can get the order to work correctly by overloading the '<' operator in my type. However, the set does not appropriately detect duplicates, and to be honest I'm not entirely sure how it does this internally. I have overloaded the '==' operator, but somehow im not sure this is what the set is actually using? So the question is how does the set determine duplicates when you add values? Here is the relevant code:
用户定义类型:
//! An element used in the route calculation.
struct RouteElem {
int shortestToHere; // Shortest distance from the start.
int heuristic; // The heuristic estimate to the goal.
Coordinate position;
bool operator<( const RouteElem& other ) const
{
return (heuristic+shortestToHere) < (other.heuristic+other.shortestToHere);
}
bool operator==( const RouteElem& other ) const
{
return (position.x == other.position.x && position.y == other.position.y);
}
};
所以当它们的位置相等时,元素是等价的,如果一个元素的组合功能小于另一个元素,则它小于另一个元素.排序有效,但集合将接受相同位置的两个元素.
So the elements are equivalent when their position is equivalent, and an element is less than another if its combined functional is less than that of the other. The sorting works, but the set will accept two elements of the same position.
推荐答案
operator==
未被 std::set
使用.元素 a
和 b
被认为相等 iff !(a < b) &&!(b < a)
operator==
is not used by std::set
. Elements a
and b
are considered equal iff !(a < b) && !(b < a)
这篇关于std::set 与用户定义的类型,如何确保没有重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::set 与用户定义的类型,如何确保没有重复
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01