将std::vector中的唯一元素插入std::set
inserting unique elements from std::vector to std::set
我有一个名为Point
的类,用于存储x和y双精度值。我有一个包含重复值的std::vector
(Point
) s。我正在计算这个向量中唯一项的个数。
我认为因为std::set
只有唯一的对象,从vector
创建set
会给我唯一的值。但我没有得到正确的结果。我重载了相等运算符。但是重复的值仍然被插入到set
.
当前结果如下…
10,10 repetitions - 1
10,10 repetitions - 1
20,20 repetitions - 1
20,20 repetitions - 1
我在等……
10,10 repetitions - 2
20,20 repetitions - 2
任何线索我错了吗?完整代码如下:
Point.h文件
#ifndef POINT_H
#define POINT_H
class Point
{
public:
Point(double x, double y);
double getX();
double getY();
Point(const Point &other);
bool operator == (const Point& p );
bool operator != (const Point& p );
private:
double _x;
double _y;
};
#endif // POINT_H
Point.cpp文件
#include "point.h"
Point::Point(double x, double y)
{
_x = x;
_y = y;
}
Point::Point(const Point &other)
{
_x = other._x;
_y = other._y;
}
double Point::getX()
{
return _x;
}
double Point::getY()
{
return _y;
}
bool Point::operator == ( const Point& p )
{
return ( (_x == p._x ) && (_y == p._y));
}
bool Point::operator != ( const Point& p )
{
return !((*this) == p );
}
main.cpp文件
#include <iostream>
#include <vector>
#include <set>
#include "Point.h"
using namespace std;
int main()
{
std::vector <Point*> pointsVector;
pointsVector.push_back(new Point(10,10));
pointsVector.push_back(new Point(10,10));
pointsVector.push_back(new Point(20,20));
pointsVector.push_back(new Point(20,20));
std::set<Point*> uniqueSet( pointsVector.begin(), pointsVector.end() );
std::set<Point*>::iterator it;
for (it = uniqueSet.begin(); it != uniqueSet.end(); ++it)
{
Point* f = *it; // Note the "*" here
int result = std::count( pointsVector.begin(), pointsVector.end(), f );
cout << f->getX() << "," << f->getY() << " repetitions - " << result << endl;
}
return 0;
}
你所有的元素都是不同的,因为你:
1)使用指针,因此您必须传递一个自定义比较器,该比较器将指针与Point
进行比较,并考虑它们指向的内容。
2)假设std::set
使用operator ==
或operator !=
,而实际上它使用operator <
。
我将有一个Point
的集合,而不是Point*
。你有理由使用指针而不是对象吗?如果没有,则使用对象。
相关文章:
- 使用std::transform将一个范围的元素添加到另一个范围中
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何从存储在std::映射中的std::集中删除元素
- 缓存std::数组的选定元素,并在c++中自动保持其一致性
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- std::矢量保存 只推送最后一个元素
- std::map:当元素不可默认构造时创建/替换元素
- 如何读/写或遍历 std::array 中的特定元素范围?
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 为什么 std::p air 的大小与其元素的大小之和不同?
- 我可以列表初始化 std::vector 并完美转发元素吗?
- 使用 std::min_element、std::max_element 查找矢量中的最小和最大元素
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 除了 std::vector 之外,是否有一个 std 容器不会复制和销毁作为类的元素?
- call call cons构件功能的std ::元素的每个元素