如何重載std:swp()std::swap()由許多std容器使用(如std::list和std::vector)在排序甚至分配過程中。但性病的實施swap()對于自定義類型來說是非常普遍的和相當低效的。因此,過載可以提高效率。std::swap()具有特定于自定義類型的實現。但是如何實現它,以便STD容器能夠使用它呢?
3 回答
慕工程0101907
TA貢獻1887條經驗 獲得超5個贊
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);
// ...
}};
FFIVE
TA貢獻1797條經驗 獲得超6個贊
namespace std{
template<>
void swap(my_type& lhs, my_type& rhs)
{
// ... blah
}}class Base{
// ... stuff ...}class Derived : public Base{
// ... stuff ...}namespace std{
template<>
void swap(Base& lha, Base& rhs)
{
// ...
}}- 3 回答
- 0 關注
- 330 瀏覽
添加回答
舉報
0/150
提交
取消
