我正在尝试做这样的事情,但是我不确定什么是最好的方法。 我究竟做错了什么?我也尝试过将double v []更改为double * v
#include <iostream>
#include <random>
using namespace std;
void PopulateVector(double v[])
{
delete v;
v = new double[5];
v[0] = 1;
v[1] = 1;
v[2] = 1;
v[3] = 1;
v[4] = 2;
}
int main()
{
double *test = new double[1];
PopulateVector(test);
for (int i = 0; i < 5; i++)
{
cout << test[i] << endl;
}
}
基于良好的评论。我做了一些修改。此版本有效,但我仍然希望void PopulateVector(double * v)或PopulateVector(double v [])有效。
#include <iostream>
#include <random>
using namespace std;
double* PopulateVector()
{
double *v = new double[5];
v[0] = 1;
v[1] = 1;
v[2] = 1;
v[3] = 1;
v[4] = 2;
return v;
}
int main()
{
double *test = new double[1];
delete[]test; // Do I need this?
test = PopulateVector();
double *test2 = new double[1];
test2 = PopulateVector();
for (int i = 0; i < 5; i++)
{
cout << test[i] << endl;
}
}
答案 0 :(得分:3)
我在做什么错了?
delete
用于数组。v
变量的本地副本。int main
返回整数我对您的建议是使用stl!
什么是最好的方法。
这是一个品味问题,但我会做类似的事情:
#include <iostream>
#include <random>
#include <vector>
std::vector<double> PopulateVector()
{
std::vector<double> v(5);
v[0] = 1;
v[1] = 1;
v[2] = 1;
v[3] = 1;
v[4] = 2;
return v;
}
int main()
{
std::vector<double> test = PopulateVector();
for (int i = 0; i < test.size(); i++)
{
std::cout << test[i] << std::endl;
}
return 0;
}
答案 1 :(得分:1)
要回答更新的问题,可以使PopulateVector(double *v)
起作用,只要该数组是由调用者而不是函数本身分配的
void PopulateVector(double * v)
{
v[0] = 1;
v[1] = 1;
v[2] = 1;
v[3] = 1;
v[4] = 2;
}
int main()
{
// Caller allocates the memory
double * test = new double[5];
PopulateVector(test);
delete[] test;
// Or even better, keep it on the stack
double test2[5];
PopulateVector(test2);
}