算法partition_copy()在SIGABRT中产生,与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;
}

使用backtrace的输出如下:

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

相关内容

  • 没有找到相关文章

最新更新