What is the correct way to remove a vector element? C++

Asked

Viewed 4,452 times

1

Could the way be the same to erase an integer vector, or an object vector? Every time an element is deleted, the vector position has to be changed ? The situation is the same by eliminating at the beginning or end ?

As an example:

int vector containing : 2 54 6 7 8

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

  • 1

    What are you doing? Give some context, show where your problem is.

  • I already edited the post to be clearer.

  • 1

    myvector.Erase (myvector.Begin()+Indice);

  • @And does the vector automatically change size after this instruction ? since if an element is eliminated its size will not stay the same.

1 answer

3


First remember to give a 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 a widget by the Dice 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 fits itself )

ex: [0,2,5,1,3] -> nameVector.Rase (nameVector.Begin()+ 2)

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

The situation is the same by eliminating at the beginning or end ?

Yes, Voce can use Erase to delete any element, including the first and last. But if you want Voce you can use it to make

nomeDoVector.pop_back();

it automatically finds who is the last and deletes.

OBS1: Voce can also delete several elements at once thus:

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

Browser other questions tagged

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