向量排序:交换过载
我想重载原始类型/对象的 std::vector 的交换函数。原因是使用 std::sort 对包含大对象的向量进行排序很慢。这是一个简单但不起作用的示例。
#include <vector>
#include <algorithm>
class Point
{
private:
double x, y;
public:
Point(double xx, double yy) : x(xx), y(yy) {}
bool operator < ( const Point& p ) const
{
return x < p.x;
}
void swap(Point &p)
{
std::swap(*this, p);
}
};
namespace std
{
void swap( Point &p1, Point &p2)
{
p1.swap(p2);
}
}
typedef std::vector<Point> TPoints;
int main()
{
Point p1(0,0);
Point p2(7,100);
TPoints points;
points.push_back(p1);
points.push_back(p2);
//Overloaded metod swap will not be called
std::sort(points.begin(), points.end());
}
不幸的是,在 std::sort 期间,没有调用重载方法。我想包含对象的向量也会出现类似的情况...感谢您的帮助...
I would like to overload swap function for std::vector of primitive types / objects. The reason is a slow sorting of vectors containing big objects using std::sort. Here is the simple but not working example.
#include <vector>
#include <algorithm>
class Point
{
private:
double x, y;
public:
Point(double xx, double yy) : x(xx), y(yy) {}
bool operator < ( const Point& p ) const
{
return x < p.x;
}
void swap(Point &p)
{
std::swap(*this, p);
}
};
namespace std
{
void swap( Point &p1, Point &p2)
{
p1.swap(p2);
}
}
typedef std::vector<Point> TPoints;
int main()
{
Point p1(0,0);
Point p2(7,100);
TPoints points;
points.push_back(p1);
points.push_back(p2);
//Overloaded metod swap will not be called
std::sort(points.begin(), points.end());
}
Unfortunately during the std::sort overloaded method is not called. I suppose the vector containing objects will be similar situation... Thanks for yout help...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实现交换的正确方法是:
但是,只有当您需要编写三巨头时才有意义(您是管理某些资源)。
你不是,所以我不明白这一点。 (所有
swap
所做的就是复制一些双精度数,就像默认的std::swap
一样。)The proper way to implement swap is:
However, it only makes sense to do this when you need to write the Big Three (you're managing some resource).
You aren't, so I don't see the point. (All your
swap
will do is copy around some doubles, just like the defaultstd::swap
would.)您必须专门化
std::swap
模板,而不是重载它。例子:
You have to specialize the
std::swap
template, not overload it.EXAMPLE:
sort可能调用了vector的swap成员函数。无论如何,你不能做你正在做的事情,重新定义 std::swap 会在幕后造成严重破坏。
另外 - 你确定 double, double 算大吗?
sort probably calls the swap member function of vector. You cant do what you are doing anyway, redefining std::swap is going to play havoc under the hood.
Plus - are you sure that double, double counts as big?