How to delete an element of a vector in C++, permanently

Asked

Viewed 34 times

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?

  • 1

    The method vector::erase, as documented here, modifies the container where it was called. The issue of your code is that by specifying vector<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 vector get_nearest to delete "permanently" one of its elements, with no copy.

  • when using vector<int>& v am then passing the address of the first element of my original vector?

  • That’s right. But to make it clear that the reference is v, I would prefer to format as vector<int> &v.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.