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 *'

Last edited on
Your function indicates that you will give back a pointer to a float

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

but you're trying to give back &nums which is a (reference to a) vector.

Make it easy on yourself - you've passed in a reference to your vector, so the function makes changes in that actual object and when its finished you don't need to return anything.

float* readNums(vector<float> &nums) //reads numbers from file to array
becomes
void readNums(vector<float> &nums) //reads numbers from file to array

and
 
return &nums;

becomes
but if it's a void function, it doesn't return a value(I think) and I need to use the numbers in the vector. Also, it cut off, what would I change "return &nums;" to in a void function? "return 0;"?
You've missed the point of passing by reference. You are passing in a vector by reference, so the vector the function gets to play with is not a copy of the original vector - it is the exact same vector in the exact same place in memory. The changes your function makes to the vector are seen by whatever called your function when your function returns.

Thats not cut off; when your function has no return (i.e. void), there is no return statement (or, if you like, you can return; or return void;)
Last edited on
closed account (zb0S216C)
A function that returns void indicates that the function returns nothing. As Moschops said (first post), if you're altering the contents of the vector by reference, then you don't need to return the vector.

Wazzak
Last edited on
okay, I got it. Thank you. Sorry for my ignorance, I am getting no guidance from the teacher or book, so I am pretty much teaching myself.
Topic archived. No new replies allowed.