我只是想知道,为什么有人写这个:
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)
我在这里忽略了重要的差异/问题吗?
我很难理解为什么直接调用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)