Pass by reference to a vector

I am not very familiar with vectors and my school book does not help much. I have been researching as much as possible but I am just lost. Here is my function and error. Please help It worked as an array but I need a vector now and it doesn't like some kind of conversion.

float* readNums(vector<float> &nums) //reads numbers from file to array
{
ifstream ins;
ofstream outs;
string line;

ins.open(infile); //opens file
if (ins.fail())
{
cerr << "Error: Cannot open " << infile << "for input." << endl;
}
if (outs.fail())
{
cerr << "Error: Cannot open " << outfile << "for output." << endl;
}

int i = 0;
int count = 0;

while (getline(ins, line))
{
nums[i] = atof(line.c_str());
i++;
}
count = i; //count of numbers
cout << "Count is " << count << endl;


ins.close(); //closes infile
return &nums;

}

error C2440: 'return' : cannot convert from 'std::vector<_Ty> *' to 'float *'
closed account (zb0S216C)
You're trying to return the address of the vector itself, not a element. In order to fix this, you need one of the following:

1) return &nums.at( n );
2) return &nums[ n ];

If you want to return a pointer to the vector itself, then you need to change your return type to this:
vector < float > *.

Also, try avoid the use of the overloaded sub-script operator on vectors. The sub-script operator doesn't throw an exception if the boundaries of the vector are exceeded. The member method at( ) throws an exception and allows the program to continue, assuming you catch the exception of course.

Wazzak
Last edited on
closed account (zwA4jE8b)
a float* cannot point to a vector, even if it is a vector of floats.

why not use
vector<float>* readNums(vector<float> &nums) //reads numbers from file to array

EDIT: damn, I was beaten to it.
Last edited on
I got it. Thank you.
Topic archived. No new replies allowed.