简体   繁体   中英

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]). 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?

The closest thing I can find is list::splice, but that's not for C-style arrays and doesn't take a predicate.

std::partition() would work.

Indeed, Example 1 on that page is separating even and odd numbers. 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM