2012-03-23 97 views
-2

如何從STL容器中選擇具有特定值的元素並將它們移動到該容器的末尾?STL容器移動選定的元素

+0

請包括您的代碼以及它如何失敗。 – bernie 2012-03-23 18:29:19

+0

具體。哪個容器? – Nawaz 2012-03-23 18:29:29

+0

我沒有指定哪個容器,因爲我想聽聽哪種容器最適合。但Vector或List可能是我的選擇。 – userbb 2012-03-23 18:34:20

回答

5

考慮到你在關於想使用std :: vector的評論,我建議使用的std ::分區或std :: stable_partition,即:

#include <algorithm> 
#include <functional> 
#include <iostream> 
#include <iterator> 
#include <vector> 

int main() 
{ 
    int init_values[] = {1, 1, 7, 3, 19, 5, 5, 4, 5, 2, 5, 8, 9, 10, 5, 1}; 
    std::vector<int> values(
     init_values, 
     init_values + sizeof(init_values)/sizeof(int) 
    ); 

    std::stable_partition(
     values.begin(), values.end(), 
     std::bind1st(std::not_equal_to<int>(), 5) 
    ); 

    std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, ", ")); 
    std::cout << "\n"; 

    return 0; 
} 

此代碼將移動的所有元素矢量等於5到矢量的末尾,保持其他元素的相對順序不變。

+0

我想知道爲什麼STL有這麼專門的算法。 – userbb 2012-03-23 20:45:12

+0

@userbb:標準庫有幾個「排序」[算法](http://en.cppreference.com/w/cpp/algorithm),具有_different用法和performance_('std :: partition','std :: stable_partition ','std :: nth_element','std :: partial_sort','std :: stable_sort','std :: sort')。 – Blastfurnace 2012-03-23 21:04:53

5

您可以嘗試使用std::partition,其謂詞返回true,表示元素不等於到目標值。如果您需要保留元素的相對順序,則還有std::stable_partition