是否有STL函数将c风格的数组拆分/拼接成更小的数组?
Are there STL functions to split/splice C-style arrays into smaller arrays?
假设我有一个c风格的数组(int numbers[10])。我想把这个数组分成一个奇数数组和一个偶数数组。此外,我想使用谓词来确定一个数字是否为奇数。
问题:我很好奇-是否有STL函数可以做到这一点?
我能找到的最接近的东西是list::splice,但这不是c风格的数组,不需要谓词。
std::partition()可以。
的确,该页上的例1正在分离偶数和奇数。它是在vector上做的,但没有理由它不能在原生数组上工作。
下面是我做的一个简短的例子:
#include <algorithm>
#include <iostream>
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
auto mid = std::partition(std::begin(a), std::end(a),
[](int n){return n%2;});
std::cout << "Odd: " << std::endl;
for (auto p = std::begin(a); p < mid; ++p)
{
std::cout << *p << std::endl;
}
std::cout << "Even: " << std::endl;
for (auto p = mid; p < std::end(a); ++p)
{
std::cout << *p << std::endl;
}
}
确实可以:std::partition
根据谓词划分序列。
auto begin = std::begin(array);
auto end = std::end(array);
auto part = std::partition(begin, end, [](int n){return n%2;});
现在[begin,part)
包含奇数值(谓词为真),[part,end)
包含偶数值(谓词为假)。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '