如何從STL容器中選擇具有特定值的元素並將它們移動到該容器的末尾?STL容器移動選定的元素
回答
考慮到你在關於想使用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到矢量的末尾,保持其他元素的相對順序不變。
我想知道爲什麼STL有這麼專門的算法。 – userbb 2012-03-23 20:45:12
@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
您可以嘗試使用std::partition
,其謂詞返回true
,表示元素不等於到目標值。如果您需要保留元素的相對順序,則還有std::stable_partition
。
- 1. 移動STL容器中的元素是否將其從該容器中移除?
- 2. STL容器插入元素
- 3. 回到STL容器元素的參考
- 4. stl容器中的搜索元素
- 5. stl容器中的常量移除元素
- 6. 什麼是STL容器來執行元素之間的移除?
- 7. 移動列表元素在STL
- 8. STL容器元素銷燬順序
- 9. 使用元素鍵迭代STL容器
- 10. 向STL容器背面添加元素
- 11. 將迭代器返回到STL容器中的元素
- 12. 使用std :: remove_reference獲取STL容器的元素迭代器
- 13. STL:容器的容器
- 14. C++ STL關聯容器:從元素獲取迭代器?
- 15. 從STL容器中移除元素時調用析構函數嗎?
- 16. Eclipse CDT無法解析STL容器中元素的方法
- 17. 檢查stl容器中元素的類型 - C++
- 18. C++ - 如何從STL容器有效的條件刪除元素?
- 19. 定位在容器元素
- 20. 從給定謂詞抽取給定stl容器中的元素到另一個容器
- 21. 用不可見內容移動元素
- 22. 容器內的固定定位元素
- 23. C++ STL容器
- 24. 移動元素?
- 25. stl兼容的容器
- 26. 移動固定定位元素的iOS 7輸入元素
- 27. 複製SDL_Surface像素爲STL容器
- 28. 移動元素進行關聯容器的
- 29. 當元素被移除時,可滾動的div容器消失
- 30. 移動插入容器元素,如果可能的話
請包括您的代碼以及它如何失敗。 – bernie 2012-03-23 18:29:19
具體。哪個容器? – Nawaz 2012-03-23 18:29:29
我沒有指定哪個容器,因爲我想聽聽哪種容器最適合。但Vector或List可能是我的選擇。 – userbb 2012-03-23 18:34:20