1 c++ sorting swap overloading
我想为基本类型/对象的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());
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,在调用std :: sort重载方法时没有调用.我想包含对象的向量将是类似的情况...感谢您的帮助......
实现交换的正确方法是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当你需要写三巨头(你正在管理一些资源)时才这样做才有意义.
你不是,所以我没有看到这一点.(你swap所做的就是复制一些双打,就像默认的std::swap那样.)