我很难理解为什么直接调用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) STL 顺序容器(如向量、双端队列、列表)支持 insert 在给定迭代器之前插入元素以支持诸如
矢量.插入(std::end(容器),container2.begin(),container2.end())
而forward_list支持insert_after。为什么 STL 维护者必须做出这样的设计选择?