1

I have been working on what I thought would just be a simple function for quite a while now. We are expected to use push_back(), but I haven't been able to get it to work.

Here's what I have right now:

void append(const vector<int>& v1, vector<int> v2)
{
    for (int x : v1)
        v2.push_back(x);
}

void println(const vector<int>& v)
{
    for (int x : v)
        cout << x << ' ';
    cout << endl;
}

int main()
{
    vector <int> v1(3, 15);
    vector <int> v2(3, 25);
    append(v1, v2);
    println(v1);
    println(v2);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

5

v2 in void append(const vector<int>& v1, vector<int> v2) is a copy of what is passed, so modifying it won't affect what is passed.

You should use reference (add &) to have the function modify what is passed.

void append(const vector<int>& v1, vector<int>& v2) // add & before v2
{
    for (int x : v1)
        v2.push_back(x);
}

If you are not expected to use push_back, std::copy is useful.

#include <algorithm>

void append(const vector<int>& v1, vector<int>& v2)
{
    std::copy(v1.begin(), v1.end(), std::back_inserter(v2));
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70