std::swap() 被许多 std 容器(例如 std::list 和 std::vector)使用排序甚至分配.
std::swap() is used by many std containers (such as std::list and std::vector) during sorting and even assignment.
但是 swap() 的 std 实现非常通用,对于自定义类型来说效率很低.
But the std implementation of swap() is very generalized and rather inefficient for custom types.
因此可以通过使用自定义类型特定实现重载 std::swap() 来提高效率.但是如何实现它才能被 std 容器使用?
Thus efficiency can be gained by overloading std::swap() with a custom type specific implementation. But how can you implement it so it will be used by the std containers?
重载 std::swap 的实现(也就是专门化它)的正确方法是将它写在同一个命名空间中作为您要交换的内容,以便可以通过 参数相关查找 (ADL) 找到它).一件特别容易的事情是:
The right way to overload std::swap's implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via argument-dependent lookup (ADL). One particularly easy thing to do is:
class X
{
// ...
friend void swap(X& a, X& b)
{
using std::swap; // bring in swap for built-in types
swap(a.base1, b.base1);
swap(a.base2, b.base2);
// ...
swap(a.member1, b.member1);
swap(a.member2, b.member2);
// ...
}
};
这篇关于如何重载 std::swap()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在 C++ 中读取和操作 CSV 文件数据?How can I read and manipulate CSV file data in C++?(如何在 C++ 中读取和操作 CSV 文件数据?)
在 C++ 中,为什么我不能像这样编写 for() 循环:In C++ why can#39;t I write a for() loop like this: for( int i = 1, double i2 = 0; (在 C++ 中,为什么我不能像这样编写 for() 循环: for(
OpenMP 如何处理嵌套循环?How does OpenMP handle nested loops?(OpenMP 如何处理嵌套循环?)
在循环 C++ 中重用线程Reusing thread in loop c++(在循环 C++ 中重用线程)
需要精确的线程睡眠.最大 1ms 误差Precise thread sleep needed. Max 1ms error(需要精确的线程睡眠.最大 1ms 误差)
是否需要“do {...} while ()"?环形?Is there ever a need for a quot;do {...} while ( )quot; loop?(是否需要“do {...} while ()?环形?)