How to print elements in a vector c++

Your function declaration and definition are not consistent, you want to generate vector from Initialize, you can do:

void Initialize(vector<int>& v);

To print vector:

void Print(const vector<int>& v);

Now you call:

vector<int> v;
Initialize(v);
Print(v);

Don’t forget to change function definition of Initialize, Print to match the new signature I provided above. Also you are redefining a local variable v which shadows function parameter, you just need to comment out that line, also pass vector by const ref:

void Print (const vector<int>& v){
  //vector<int> v;
  for (int i=0; i<v.size();i++){
    cout << v[i] << endl;
  }
}

Leave a Comment