0
I don’t know much about the "pass-by-value" of C/C++, and I don’t know when to pointer or not to a function argument. Next is the code I have:
Struct Customer {
....
}
int get_nearest (int n, vector<int> v) {
....
v.erease(v.begin(), index);
}
int get_ticket() {
....
for (Customer e : customers) {
cout << get_nearest(e.money, prices) << "\n";
}
}
The method get_nearest(...)
calls the method erease(...
) that I understand that removes one of the elements of the vector v
. Therefore, by calling get_nearest(...)
as an aid to the method get_ticket()
, I realize that the vector I pass as argument is not permanently modified, since I get the following result:
By calling :
int main() {
vector<int> v = {5, 3, 7, 8, 5};
get_ticket(4, v);
}
the output generated is:
Vector: {5, 7, 8, 5}
Selected element: 3
Vector {5, 3, 7, 5}
Selected element: 8
Vector {5, 7, 8, 5}
Selected element: 3
However, in the third iteration, where the selected element is 3 again, it should actually return -1, since the value 3 should have been permanently deleted after the first iteration.
Because my vector prices
is only being changed temporarily, and with each new iteration it returns to its initial state?
The method
vector::erase
, as documented here, modifies the container where it was called. The issue of your code is that by specifyingvector<int> v
as parameter, you expect the vector as value, not its reference. Thus, a copy will be made by invoking this function. See more here. Ask therefore for a reference to the function vectorget_nearest
to delete "permanently" one of its elements, with no copy.– Luiz Felipe
when using
vector<int>& v
am then passing the address of the first element of my original vector?– Pirategull
That’s right. But to make it clear that the reference is
v
, I would prefer to format asvector<int> &v
.– Luiz Felipe