我有一個向量,我想使用STL算法有效地將第二部分向量分解爲另一個向量。這裏是一個辦法,我看要做到這一點,但預計在至少有更加高效和簡潔的答案,或者,一個使用STL算法:如何將一個向量的後半部分移動到另一個向量中?
std::vector<Entry> &entries = someFunction();
int numEntries = entries.size();
// Assume numEntries is greater than or equal to 2.
std::vector<Entry> secondEntries;
std::vector<Entry>::iterator halfway = entries.begin() + numEntries/2;
std::vector<Entry>::iterator endItr = entries.end()
// Copy the second half of the first vector in the second vector:
secondEntries.insert(secondEntries.end(), halfway, endItr);
// Remove the copied entries from the first vector:
entries.erase(halfway, endItr);
唯一的優化是爲'secondEntries'保留足夠的大小,以便不需要重新分配。除此之外,簡單複製元素會更有效率嗎? – mfontanini 2012-08-13 17:03:56
@mfontanini對於隨機訪問迭代器,「vector」的insert是否已經做到了這一點? – 2012-08-13 17:04:38
順便說一句,你可以創建矢量插入數據'std :: vector secondEntries(halfway,endItr);' –
RiaD
2012-08-13 17:05:07