2012-08-13 38 views
1

我有一個向量,我想使用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); 
+0

唯一的優化是爲'secondEntries'保留足夠的大小,以便不需要重新分配。除此之外,簡單複製元素會更有效率嗎? – mfontanini 2012-08-13 17:03:56

+0

@mfontanini對於隨機訪問迭代器,「vector」的insert是否已經做到了這一點? – 2012-08-13 17:04:38

+1

順便說一句,你可以創建矢量插入數據'std :: vector secondEntries(halfway,endItr);' – RiaD 2012-08-13 17:05:07

回答

4

回過頭來,請記住確保您使用自己的算法迭代器,而不是(必須)使用容器。所以,如果你有這樣的:

void foo(const std::vector<Entry>& v) { /* ... */ } 

現在你停留在這樣的情況:

std::vector<Entry> entries = someFunction(); 

// have to split entries! make more containers? :(
foo(first_half(entries)); 
foo(second_half(entries)); 

考慮使用迭代器來代替:

// or a template, if it doesn't hurt 
void foo(std::vector<Entry>::const_iterator first, 
     std::vector<Entry>::const_iterator second) { /* ... */ } 

所以,現在你代表範圍,而不是容器:

std::vector<Entry> entries = someFunction(); 

// easy to split entries! :) 
auto middle = entries.begin() + entries.size()/2; 
foo(entries.begin(), middle); 
foo(middle + 1, entries.end()); 

這限制了您製作不必要的容器和分配的數量。


有了這樣的方式,在C++ 11,你可以做到這一點(其餘是相同的):

// *Move* the second half of the first vector in the second vector:   
secondEntries.insert(secondEntries.end(), 
         std::make_move_iterator(halfway), 
         std::make_move_iterator(endItr)); 

如果Entry有一個移動構造函數,該move_iterator適配器將確保它在插入過程中使用(如果它不是正常的複製)。在C++ 03中,你擁有的可能是最好的。

1

std::move如果你有機會到可以做得更好一個C++ 11編譯器和可移動對象。

請注意,您仍然需要從第一個向量中清除它們。

0

執行此任務的方法還有其他幾種,例如使用複製算法和插入迭代器。

但算法的這些行動的複雜性將永遠是O(n)由於矢量容器的性質。 Vector不是一個允許在O(1)(常量)時間內將大塊數據從一個容器移動到另一個容器的列表。取決於特定的STL實現方式,一種方式可以比另一種方式好10-20%,但不太可能超過這一點。

如果您的容器的數據類型允許移動語義,並且您有這些語言功能可用,這肯定會有所幫助。但這更多的是處理容器中的數據對象而不是容器本身。

相關問題