Which way to delete element of a vector correctly? C ++

0

Can the same way be to delete an integer vector, or an object vector? Whenever an element is deleted, does the vector position have to be changed? Is the situation the same eliminating at the beginning or at the end?

As an example:

vector of type int containing: 2 54 6 7 8

The objective in my problem would be to eliminate through index, if index was 0, would be eliminated the number 2, and the vector would be with: 54 6 7 8

    
asked by anonymous 25.01.2017 / 22:58

1 answer

3

First remember to give an include

#include <vector>

2- Create your vector

std::vector <int> nomeDoVector;

(answering the first question, you can create vector of other things just change the "int" field, and it works the same way)

3- To delete an element from the index use:

nomeDoVector.erase (nomeDoVector.begin()+ 2); //apaga o 3º elemento

or pass a variable, in this case int i = 5;

nomeDoVector.erase (nomeDoVector.begin()+ i); //i = 5 apaga o 6º elemento

(answering the second question, the vector adjusts itself)

ex: [0.2,5,1,3] - > nameVector.erase (name ofVector.begin () + 2)

result: [0,2,1,3] - > see that now the number "1" is the 3rd.

Is the same situation eliminating at the beginning or at the end?

Yes, you can use erase to delete any element, including the first and last. But if you want you can use it to facilitate the

nomeDoVector.pop_back();

It automatically finds who the last is and deletes.

NOTE: You can also delete multiple items at once like this:

nomeDoVector.erase(nomeDoVector.begin(),nomeDoVector.begin()+3);//apaga os elementos das posições 0,1 e 2.
    
26.01.2017 / 12:49