Reputation: 21
I have a vector with integer elements {1,2,3,4} and I was trying to remove the last element in my func method. It worked fine when I used pop_back() and back(). But when I used an iterator in the method, it said the last element is still 4.
Also, if I tried to print the last element of the vector back in my main method, it still outputs 4.
Can someone kindly explain to me what I should do if I want to change the content of my vector in a method other than main?
My code:
using namespace std;
void func(vector<int> array) {
array.pop_back();
cout << "array.back() = " << array.back() << endl;
vector <int>::iterator it = array.end();
cout << "it.end() = " << (*it) << endl;
}
int main(void) {
vector <int> ar;
ar.push_back(1);
ar.push_back(2);
ar.push_back(3);
ar.push_back(4);
func(ar);
cout << "In main = " << ar.back() << endl;
return 0;
}
It outputs:
array.back() = 3
it.end() = 4
In main = 4
Upvotes: 0
Views: 317
Reputation: 1260
You're passing the vector as a value, which means it's copied in the function. If you want to modify it in the function you either need to pass it as a reference (&
) or a pointer (*
) so that the data in the original vector gets modified, not the copy.
void func(vector<int>& array) // reference
void func(vector<int>* array) // pointer
I recommend using a reference here, as you won't need to worry about null pointers or need to change any of your method (with a pointer you would need to change the '.
's to '->
's).
Upvotes: 4
Reputation: 5336
You need to change passing your argument to func()
to be by reference instead of by value like this:
#include <iostream>
#include <vector>
using namespace std;
void func(vector<int>& array) {
array.pop_back();
cout << "array.back() = " << array.back() << endl;
vector <int>::iterator it = array.end();
cout << "it.end() = " << (*it) << endl;
}
int main(void) {
vector <int> ar;
ar.push_back(1);
ar.push_back(2);
ar.push_back(3);
ar.push_back(4);
func(ar);
cout << "In main = " << ar.back() << endl;
return 0;
}
then the output becomes:
array.back() = 3
it.end() = 4
In main = 3
Otherwise, you are modifying a copy of the vector that you passed to func()
, but not the original one.
Upvotes: 0