C++11 gcc 4.9.2 算法 partition_copy() 产生 SIGABRT,适用于 back_inserter

C++11 gcc 4.9.2 algorithm partition_copy() results in SIGABRT, works with back_inserter

我正在尝试将 vector 分成偶数和奇数。我调整了两个输出容器的大小以确保它们足够大 - 但 partition_copy 对我来说仍然会导致 SIGBART,即使它在我使用 back_inserter 时有效。这是我的代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool is_even(int num)
{
    return (num % 2 == 0);
}

void print_vector(const vector<int> & VecRef)
{
    cout << endl;
    cout << "Contents of the vector is : " << endl;
    for (auto it = VecRef.begin(); it != VecRef.end(); ++it) {
        cout << "[" << it - VecRef.begin() << "] : " << *it << endl;
    }
}

int main() 
{
    vector<int> NumbersVec;

    for (int cnt = 1; cnt < 10; ++cnt)
        NumbersVec.push_back(cnt);

    vector<int> EvenVec, OddVec;
    unsigned countEven = count_if(NumbersVec.begin(), NumbersVec.end(), is_even);

    cout << "Evens : " << countEven << endl; //Prints 4
    cout << "Odds : " << NumbersVec.size() - countEven << endl; //Prints 5

    EvenVec.resize(countEven);
    OddVec.resize(NumbersVec.size() - countEven);

    partition_copy(NumbersVec.begin(), NumbersVec.end(), EvenVec.begin(), OddVec.end(), is_even);

    // partition_copy(NumbersVec.begin(), NumbersVec.end(), back_inserter(EvenVec), back_inserter(OddVec), is_even); This works...

    print_vector(EvenVec);
    print_vector(OddVec); // <== this one crashes

    return 0;
}

带回溯的结果输出如下:

Evens : 4
Odds : 5

Contents of the vector is : 
[0] : 2
[1] : 4
[2] : 6
[3] : 8

Contents of the vector is : 
[0] : 0
[1] : 0
[2] : 0
[3] : 0
[4] : 0
*** Error in `./82-AlgorithmSort': free(): invalid next size (fast): 0x0000000000fb1030 ***
======= Backtrace: =========
/usr/lib/libc.so.6(+0x7198e)[0x7f849992c98e]
/usr/lib/libc.so.6(+0x76dee)[0x7f8499931dee]
/usr/lib/libc.so.6(+0x775cb)[0x7f84999325cb]
./82-AlgorithmSort(_ZN9__gnu_cxx13new_allocatorIiE10deallocateEPim+0x20)[0x404712]
./82-AlgorithmSort(_ZNSt16allocator_traitsISaIiEE10deallocateERS0_Pim+0x2b)[0x404579]
... snip ...
Aborted (core dumped)

您传递了错误的迭代器:

partition_copy(NumbersVec.begin(), NumbersVec.end(), 
               EvenVec.begin(), OddVec.end(), is_even);
                                      ↑↑↑↑↑↑

你的意思是:

partition_copy(NumbersVec.begin(), NumbersVec.end(), 
               EvenVec.begin(), OddVec.begin(), is_even);