gpt4 book ai didi

C++11 gcc 4.9.2 算法 partition_copy() 导致 SIGABRT,与 back_inserter 一起工作

转载 作者:行者123 更新时间:2023-11-30 03:53:02 25 4
gpt4 key购买 nike

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

关于C++11 gcc 4.9.2 算法 partition_copy() 导致 SIGABRT,与 back_inserter 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com