我正在尝试从函数返回一个 vector 。我的代码编译通过,我检查了我的函数并认为错误来自返回部分。它编译得很好(使用 Cygwin),但是在运行它时,我收到一个 Aborted (core dumped) 错误。 这是我的代码:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//function that returns the square
int f(int n)
{
return n*n;
}
vector<int> myVec;
int counter = 0;
//function that uses f on all elements in a list
vector<int> map(vector<int> something)
{
//base case
if(counter == something.size())
{
/*cout << "hello" << endl;
for (int i=0; i<counter; i++)
{
cout << "vector: " << myVec[i] << endl;
}*/
counter=0;
return myVec;
}
//recursion
else
{
//cout << "counter: " << counter << endl;
int n = f(something[counter]);
//cout << "n: " << n << endl;
myVec.push_back(n);
//cout << "vector: " << myVec[counter] << endl;
counter++;
map(something);
}
}
int main()
{
//making vectors
vector<int> L;
vector<int> L1;
vector<int> L2;
for (int i=0; i<20; i++)
{
L.push_back(i);
}
L1 = map(L);
}
代码最初来自类文件。
最佳答案
在你的递归中,你不返回任何东西。该函数应返回一个 Vector。
在您的情况下,如果函数在第一次调用时进入“else”情况会怎样?它重新进入 map() 直到满足条件,然后返回一个 vector 。该 vector 被传递给之前的递归调用并立即被删除,因为它不再被传递。
这里的解决方案是将 else-case 的最后一行更改为
return map(something);
因此值不会丢失并正确传递给原始调用者(您的主函数)。
关于从函数返回 vector 时 C++ 中止(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43178417/