How do I add or remove a vector element?

-1

From a vector, how do I remove or add an element?

    
asked by anonymous 17.05.2016 / 12:45

1 answer

0

You can not remove an element from a vector.

Imagine that the vector is like a parking lot and its places. You can not remove a place, you can only change the content of each place.

An approximate thing you can do with the vector is to know how many elements are "busy", and keep those elements at the beginning of the vector.

int vetor[100]; // capacidade para 100 elementos
size_t nvetor = 0; // zero elementos

vetor[nvetor++] = 42; // vetor[0] = 42;
vetor[nvetor++] = -1; // vetor[1] = -1;
vetor[nvetor++] = 0;  // vetor[2] = 0;

To "remove" vector [1], you can do the following

// copia elementos para tras
for (int k = 1; k < nvetor - 1; k++) vetor[k] = vetor[k + 1];
// ajusta nvetor
nvetor--;

For verification

for (k = 0; k < nvetor; k++) printf("%d ", vetor[k]);
    
18.05.2016 / 14:00