STL容器移动选定的元素
STL Container move selected elements
如何从STL容器中选择具有特定值的元素,并将它们移动到该容器的末尾?
考虑到您对想要使用std::vector发表了评论,我建议使用std::partition或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的所有元素移动到向量的末尾,保持其余元素的相对顺序。
您可以尝试将std::partition
与谓词一起使用,该谓词为不等于目标值的元素返回true
。如果需要保留元素的相对顺序,则还有std::stable_partition
。
相关文章:
- 为什么复制而不是移动数据元素?
- 设计将引用元素移动到开头的数据结构.C++
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 如何将数组中的元素向右移动?
- 在同一容器中移动元素
- 移动数组C++中的特定元素
- C++:我可以重用/移动 std::list 元素从中间到结尾吗?
- 在数组的开头添加一个元素并移动其余元素,但保留大小
- 如何将 std::vector 的某些元素移动到向量中的新索引?
- boost multi_index - 如果元素类型仅支持移动语义,如何遍历它?
- 在 C++ 中移动数组元素
- 从标准容器中移动元素是否合法?
- 为什么我不能将元素移动到不可复制的向量中?
- 如何将 std::vector 中的元素移动 1
- 将列表元素移动到列表末尾的函数多次不起作用
- 将 vector<vector> 的最后一个元素移动到<int>开头
- 将数组的特定元素移动到新数组
- 在 C 和 C++ 中,如何将数组中的某些元素移动到新数组中
- 我可以将一个QObject数组的单个元素移动到另一个QThread吗
- 将向量元素移动到向量的后面