3 回答

TA貢獻1880條經驗 獲得超4個贊
我會這樣做:
#include <algorithm>
#include <vector>
#include <utility>
int main(int argc, char* argv[])
{
std::vector<int> v1 = { 1, 2, 3, 4, 5 };
{
std::vector<int> v2(v1.begin(), v1.end());
std::copy(v1.begin(), v1.end(), std::back_inserter(v2));
std::swap(v1, v2);
}
return 0;
}
編輯:我添加了一個稍微更有效的版本。
#include <algorithm>
#include <vector>
#include <utility>
int main(int argc, char* argv[])
{
std::vector<int> v1 = { 1, 2, 3, 4, 5 };
{
typedef std::move_iterator<decltype(v1)::iterator> VecMoveIter;
std::vector<int> v2(v1);
std::copy(VecMoveIter(v1.begin()), VecMoveIter(v1.end()), std::back_inserter(v2));
v1 = std::move(v2);
}
return 0;
}

TA貢獻2080條經驗 獲得超4個贊
用于附加多個副本插槽。
int main() {
std::vector<int> V;
V.push_back(1);
V.push_back(2);
int oldSize = V.size();
int newSize = oldSize;
int nDupSlot = 4;
V.resize(nDupSlot * oldSize);
for(int i=0; i<(nDupSlot-1); ++i) {
std::copy_n(V.begin(), oldSize, V.begin() + newSize);
newSize = newSize + oldSize;
}
for(int i =0; i<V.size(); ++i) {
std::cout<<V[i];
}
return 0;
}
輸出:
12121212
- 3 回答
- 0 關注
- 409 瀏覽
添加回答
舉報