1

I'm trying to write a function that will take in std::vector and the file name then write every integer from the file to vector. I wrote a simple void function which I have tested with the debugger and it worked fine but when I called it from the main function it returned empty std::vector.

    #include<iostream>
    #include<vector>
    #include<fstream>
    #include<string>
    using namespace std;

    void fill_vector(vector<int> v, string file_name) 
    {
        ifstream ifs(file_name);
        int n;
        while (ifs >> n)
            v.push_back(n);
    }

    int main()
    {
        vector<int> vec;
        string s = "integers.txt";
        fill_vector(vec, s);
    }
Rama
  • 3,222
  • 2
  • 11
  • 26
G.Q
  • 33
  • 5
  • You're passing a copy of the vector to the `fill_vector` function, change its signature to `void fill_vector(vector &v, string file_name)` – Colin Dec 13 '16 at 11:41
  • You don't actually check whether the file is opened successfully or not. – Paul R Dec 13 '16 at 11:41

4 Answers4

4

That's because fill_vector takes it's vector argument by value. It copies the vector you pass into and then fills that vector which is not what you want because that copy will be lost by the end of the function. You want the actual vector to change.

This is done by passing the vector as a reference instead, change your function signature to (note the ampersand &) :

void fill_vector(vector<int>& v, string file_name) 
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

As an alternative to passing a vector by non-const reference, you could have fill_vector return the vector by value. In C++11 this is as efficient as passing a non-const reference.

vector<int> fill_vector(string file_name) 
{
  ifstream ifs(file_name);
  if(!ifs.open())
    return {0};
  vector<int> vec;     
  int n;
  while (ifs >> n)
    vec.push_back(n);
  return vec;
}
Community
  • 1
  • 1
Jack Deeth
  • 3,062
  • 3
  • 24
  • 39
0
void fill_vector(vector<int>& v, string file_name)
//                          ^ you forgot this
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
0

You should pass your vector by reference if you want to edit it inside the function:

void fill_vector(vector<int>& v, string file_name)
____________________________^_____________________
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160