相关疑难解决方法(0)

iter_swap有什么意义?

我只是想知道,为什么有人写这个:

std::iter_swap(i, k);
Run Code Online (Sandbox Code Playgroud)

而不是这个?

std::swap(*i, *k);   // saved a few keystrokes!
Run Code Online (Sandbox Code Playgroud)

然后我查看了实现iter_swap,当然它只使用swap而不是std::swap因为我们已经在namespace std,但无论如何.这引出了我的下一个问题:

为什么有人写这个:

using std::swap;
swap(a, b);
Run Code Online (Sandbox Code Playgroud)

而不是这个?

std::iter_swap(&a, &b);   // saved an entire line of code!
Run Code Online (Sandbox Code Playgroud)

我在这里忽略了重要的差异/问题吗?

c++ templates swap namespaces argument-dependent-lookup

34
推荐指数
2
解决办法
2013
查看次数

std :: iter_swap需要ValueSwappable args vs std :: swap需要Move Assignable args

我很难理解为什么直接调用std::swap()下面的代码导致编译错误,而使用std::iter_swap编译时没有任何错误.

iter_swap()对比swap()- 有什么区别?,iter_swap最后打电话std::swap但他们的行为仍然不同.

#include <iostream>
#include <vector>

class IntVector {
    std::vector<int> v;
    IntVector& operator=(IntVector); // not assignable
public:
    void swap(IntVector& other) {
        v.swap(other.v);
    }
};
void swap(IntVector& v1, IntVector& v2) {
    v1.swap(v2);
}

int main()
{
    IntVector v1, v2;
//  std::swap(v1, v2); // compiler error! std::swap requires MoveAssignable
    std::iter_swap(&v1, &v2); // OK: library calls unqualified swap()
}
Run Code Online (Sandbox Code Playgroud)

c++ swap move-semantics c++11

4
推荐指数
1
解决办法
118
查看次数