我想为原始类型/对象的 std::vector 重载交换函数。原因是使用 std::sort 对包含大对象的 vector 进行缓慢排序。这是一个简单但不起作用的示例。
#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 重载方法没有被调用。我想包含对象的 vector 也会有类似的情况……谢谢你的帮助……
最佳答案
实现交换的正确方法是:
class foo
{
public:
void swap(foo& pOther)
{
using std::swap; // enable ADL
swap(member1, pOther.member1); // for all members
}
};
// allows swap to be found with ADL (place in same namespace as foo)
void swap(foo& pFirst, foo& pSecond)
{
pFirst.swap(pSecond);
}
// allows swap to be found within std
namespace std
{
// only specializations are allowed to
// be injected into the namespace std
template <>
void swap(foo& pFirst, foo& pSecond)
{
pFirst.swap(pSecond);
}
}
但是,只有当您需要编写三巨头(您是 managing some resource )时才有意义。
你不是,所以我不明白这一点。 (所有你的 swap
都会做的就是复制一些 double ,就像默认的 std::swap
一样。)
关于c++ - vector 排序 : swap overload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3704868/