[英]Are there STL functions to split/splice C-style arrays into smaller arrays?
假設我有一個C樣式的數組(整數number [10])。 我想將數組拆分為奇數數組和偶數數組。 此外,我想使用謂詞來確定數字是否為奇數。
問題 :我很好奇-是否有STL函數可以做到這一點?
我能找到的最接近的東西是list :: splice,但這不是C風格的數組,並且沒有謂詞。
std :: partition()將起作用。
實際上,該頁面上的示例1正在分離偶數和奇數。 它是在向量上完成的,但是沒有理由在本地數組上不起作用。
這是我處理的一個簡單示例:
#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)
包含奇數(其謂詞為true), [part,end)
包含偶數(其謂詞為false)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.