是否有STL函数将c风格的数组拆分/拼接成更小的数组?

Are there STL functions to split/splice C-style arrays into smaller arrays?

本文关键字:数组 拼接 拆分 函数 风格 是否 STL      更新时间:2023-10-16

假设我有一个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)包含偶数值(谓词为假)。