Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erasing() an element in a vector doesn't work

Tags:

c++

vector

I have a vector. I need to delete the last 3 elements in it. Described this logic. The program crashes. What could be the mistake?

vector<float>::iterator d = X.end();
    for (size_t i = 1; i < 3; i++) {
        if (i == 1) X.erase(d);
        else X.erase(d - i);
    }
like image 298
dbUser11 Avatar asked Apr 15 '20 20:04

dbUser11


People also ask

How do I remove one element from a vector?

All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.

How do you delete an element from a vector by its value?

You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector. erase(std::remove(myVector. begin(), myVector.

How do I remove an element from a vector string?

To remove all copies of an element from a vector , you can use std::remove like this: v. erase(std::remove(v. begin(), v.


2 Answers

If there are at least 3 items in the vector, to delete the last 3 items is simple -- just call pop_back 3 times:

#include <vector>
#include <iostream>

int main() 
{
    std::vector<float> v = { 1, 2, 3, 4, 5 };
    for (int i = 0; i < 3 && !v.empty(); ++i)
       v.pop_back();

    for ( const auto &item : v ) std::cout << item << ' ';
        std::cout << '\n';
}

Output:

1 2
like image 109
PaulMcKenzie Avatar answered Sep 23 '22 06:09

PaulMcKenzie


It is undefined behavior to pass the end() iterator to the 1-parameter erase() overload. Even if it weren't, erase() invalidates iterators that are "at and after" the specified element, making d invalid after the 1st loop iteration.

std::vector has a 2-parameter erase() overload that accepts a range of elements to remove. You don't need a manual loop at all:

if (X.size() >= 3)
    X.erase(X.end()-3, X.end());

Live Demo

like image 25
Remy Lebeau Avatar answered Sep 22 '22 06:09

Remy Lebeau