您如何复制STL容器?
// big containers of POD
container_type<pod_type> source;
container_type<pod_type> destination
// case 1
destination = source;
// case 2
destination.assign(source.begin(), source.end());
// case 3 assumes that destination.size() >= source.size()
copy(source.begin(), source.end(), destination.size());
我尽可能使用情况1。容器类型不同时,我使用情况2。当目标大于源且要保留其余元素时,需要情况3。
但是对于非POD元素和具有非零构造/析构成本的元素呢?情况3是否比情况2更好?如果目标大于源,则实现可能会执行相当意外的操作。这是Visual Studio 2008在情况2中所做的事情。
- 销毁目标的所有元素。
- 然后调用复制构造函数与目标大小相同次数。为什么?
- 将源的所有元素分配给对应的目标元素。
- 销毁目标的额外元素。
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
struct A {
A() { cout << "A()\n"; }
A(const A&) { cout << "A(const A&)\n"; }
A& operator=(const A&) {
cout << "operator=\n";
return *this;
}
~A() { cout << "~A()\n"; }
};
int main() {
list<A> source(2);
vector<A> desrination1(3);
vector<A> desrination2(3);
cout << "Use assign method\n";
desrination1.assign(source.begin(), source.end());
cout << "Use copy algorithm\n";
copy(source.begin(), source.end(), desrination2.begin());
desrination2.resize(2);
cout << "The End" << endl;
return 0;
}
copy(source.begin(), source.end(), destination.size());
处停止阅读。假设使用的是std::copy()
(我永远不明白为什么输入这五个字符会有多难),第三个参数是错误的。 - sbi