【问题标题】:C++11 gcc 4.9.2 algorithm partition_copy() results in SIGABRT, works with back_inserterC++11 gcc 4.9.2 算法 partition_copy() 产生 SIGABRT,与 back_inserter 一起使用
【发布时间】:2015-05-20 02:22:38
【问题描述】:

我正在尝试将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)

【问题讨论】:

    标签: c++ c++11 gcc stdvector stl-algorithm


    【解决方案1】:

    你传递了错误的迭代器:

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

    你的意思是:

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

    【讨论】:

    • 啊啊谢谢没看到那个彩虹色的小虫子。
    猜你喜欢
    • 2015-10-26
    • 1970-01-01
    • 2017-07-30
    • 2015-11-28
    • 1970-01-01
    • 2017-10-19
    • 2012-11-15
    • 1970-01-01
    相关资源
    最近更新 更多