How to add or remove a vector element?

Asked

Viewed 4,866 times

-1

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

  • You mean in the sense of resizing the array or there is a logic to be maintained in your array, maintaining a data structure?

  • Welcome to SOPT, could [Edit] your question and clarify the specific problem or add other details as some solution attempt. See the [Ask] page for help clarifying this question.

1 answer

0

You cannot remove an element from a vector.

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

An approximate thing you can do with the vector, is to know how many elements are "occupied", and keep these elements in 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" the 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]);

Browser other questions tagged

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