如果想要在C++程序中用vector传递一个大内存,用swap是比较快的方法,不过传递之后,原始数据就不存在了。
如果后续不再使用原数据,用swap会比较好。
#include <iostream> #include <ctime> #include <vector> using namespace std; int main() { int length = 10000000; vector<double> vecsrc; vector<double> vecdst1, vecdst2, vecdst3; for (int i = 0; i < length; i++) { vecsrc.emplace_back(rand()); } clock_t t1 = clock(); vecdst1 = vecsrc; clock_t t2 = clock(); cout << "t1:" << t2 - t1 << endl <<"size: " << vecsrc.size()<<" "<< vecdst1.size() << endl; vecdst2.resize(vecsrc.size()); copy(vecsrc.begin(), vecsrc.end(), vecdst2.begin()); clock_t t3 = clock(); cout << "t2:" << t3 - t2 << endl << "size: " << vecsrc.size()<<" "<< vecdst2.size() << endl; vecsrc.swap(vecdst3); clock_t t4 = clock(); cout << "t3:" << t4 - t3 << endl << "size: " << vecsrc.size()<<" "<< vecdst3.size() << endl; return 0; }