[英]Are there STL functions to split/splice C-style arrays into smaller arrays?
Let's say I have a C-style array (int numbers[10]). 假设我有一个C样式的数组(整数number [10])。 I want to split the array into an array of odd numbers and an array of even numbers.
我想将数组拆分为奇数数组和偶数数组。 Further, I'd like to use a predicate to determine if a number is odd.
此外,我想使用谓词来确定数字是否为奇数。
Question : I am curious - are there STL functions that can do this? 问题 :我很好奇-是否有STL函数可以做到这一点?
The closest thing I can find is list::splice, but that's not for C-style arrays and doesn't take a predicate. 我能找到的最接近的东西是list :: splice,但这不是C风格的数组,并且没有谓词。
std::partition() would work. std :: partition()将起作用。
Indeed, Example 1 on that page is separating even and odd numbers. 实际上,该页面上的示例1正在分离偶数和奇数。 It's doing it on a vector, but there's no reason it wouldn't work on native arrays.
它是在向量上完成的,但是没有理由在本地数组上不起作用。
Here's a quick example I worked up: 这是我处理的一个简单示例:
#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;
}
}
Indeed you can: std::partition
partitions a sequence according to a predicate. 实际上,您可以:
std::partition
根据谓词对序列进行分区。
auto begin = std::begin(array);
auto end = std::end(array);
auto part = std::partition(begin, end, [](int n){return n%2;});
Now [begin,part)
contains the odd values (for which the predicate is true), and [part,end)
contains the even values (for which the predicate is false). 现在
[begin,part)
包含奇数(其谓词为true), [part,end)
包含偶数(其谓词为false)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.