By dau_man

2009-05-17 17:59:36 8 Comments

I have a std::vector<int>, and I want to delete the n'th element. How do I do that?

std::vector<int> vec;




@R.hatam 2019-04-26 20:04:55

the fastest way (for programming contests by time complexity() = constant)

can erase 100M item in 1 second;

    vector<int> it = (vector<int>::iterator) &vec[pos];

and most readable way : vec.erase(vec.begin() + pos);

@Marshall Clow 2019-06-18 05:03:09

This is very non-portable; it will work with libstdc++, but not libc++, and not with MSVC. vector<int>::iterator is not necessarily the same as int *

@Jonathan Wakely 2019-06-18 19:23:45

It's disgusting, I think I'll change libstdc++ to stop it from working.

@meenachinmay 2018-08-23 09:03:31

here is one more way to do this if you want to delete a element by finding this with its value in vector,you just need to do this on vector.

vector<int> ar(n);
ar.erase(remove(ar.begin(), ar.end()), (place your value here from vector array));

it will remove your value from here. thanks

@cammando 2016-06-18 22:14:11

To delete an element use the following way:

// declaring and assigning array1 
std:vector<int> array1 {0,2,3,4};

// erasing the value in the array

For a more broad overview you can visit:

@L. F. 2019-02-07 10:13:07

Consider using cppreference. See this, this, etc.

@Eswaran Pandi 2016-05-04 11:06:07

The erase method will be used in two ways:

  1. Erasing single element:

    vector.erase( vector.begin() + 3 ); // Deleting the fourth element
  2. Erasing range of elements:

    vector.erase( vector.begin() + 3, vector.begin() + 5 ); // Deleting from fourth element to sixth element

@Clay J 2017-09-18 15:18:54

If you have an unordered vector you can take advantage of the fact that it's unordered and use something I saw from Dan Higgins at CPPCON

template< typename TContainer >
static bool EraseFromUnorderedByIndex( TContainer& inContainer, size_t inIndex )
    if ( inIndex < inContainer.size() )
        if ( inIndex != inContainer.size() - 1 )
            inContainer[inIndex] = inContainer.back();
        return true;
    return false;

Since the list order doesn't matter, just take the last element in the list and copy it over the top of the item you want to remove, then pop and delete the last item.

@theferrit32 2018-03-15 18:57:02

I think this is the best answer if the vector is unordered. It does not rely on the assumption that iterator + index will actually give you back the iterator position at that index, which is not true of all iterable containers. It is also constant complexity instead of linear by taking advantage of the back pointer.

@Rian Quinn 2016-10-25 15:29:34

The previous answers assume that you always have a signed index. Sadly, std::vector uses size_type for indexing, and difference_type for iterator arithmetic, so they don't work together if you have "-Wconversion" and friends enabled. This is another way to answer the question, while being able to handle both signed and unsigned:

To remove:

template<class T, class I, class = typename std::enable_if<std::is_integral<I>::value>::type>
void remove(std::vector<T> &v, I index)
    const auto &iter = v.cbegin() + gsl::narrow_cast<typename std::vector<T>::difference_type>(index);

To take:

template<class T, class I, class = typename std::enable_if<std::is_integral<I>::value>::type>
T take(std::vector<T> &v, I index)
    const auto &iter = v.cbegin() + gsl::narrow_cast<typename std::vector<T>::difference_type>(index);

    auto val = *iter;

    return val;

@Varun Garg 2016-05-20 21:07:11

Actually, the erase function works for two profiles:

  • Removing a single element

    iterator erase (iterator position);
  • Removing a range of elements

    iterator erase (iterator first, iterator last);

Since std::vec.begin() marks the start of container and if we want to delete the ith element in our vector, we can use:

vec.erase(vec.begin() + index);

If you look closely, vec.begin() is just a pointer to the starting position of our vector and adding the value of i to it increments the pointer to i position, so instead we can access the pointer to the ith element by:


So we can write:

vec.erase(&vec[i]); // To delete the ith element

@bitwise 2018-04-11 16:11:25

-1 The last line does not compile (at least in VS2017). The code assumes that vector::iterator is implicitly constructible from a raw pointer, which is not required by the standard.

@Nishant Singh 2019-05-09 06:50:42

This is true especially for debug iterators

@Fabian 2016-05-12 14:28:03

If you work with large vectors (size > 100,000) and want to delete lots of elements, I would recommend to do something like this:

int main(int argc, char** argv) {

    vector <int> vec;
    vector <int> vec2;

    for (int i = 0; i < 20000000; i++){

    for (int i = 0; i < vec.size(); i++)
        if( %3 != 0)

    vec = vec2;
    cout << vec.size() << endl;

The code takes every number in vec that can't be divided by 3 and copies it to vec2. Afterwards it copies vec2 in vec. It is pretty fast. To process 20,000,000 elements this algorithm only takes 0.8 sec!

I did the same thing with the erase-method, and it takes lots and lots of time:

Erase-Version (10k elements)  : 0.04 sec
Erase-Version (100k elements) : 0.6  sec
Erase-Version (1000k elements): 56   sec
Erase-Version (10000k elements): ...still calculating (>30 min)

@Regis Portalez 2016-05-12 14:34:39

how does this answer the question?

@Roddy 2016-06-09 20:30:18

Interesting, but not relevant to the question!

@user202729 2016-09-21 04:17:52

Won't a in-place algorithm faster?

@RiaD 2017-04-05 12:19:10

that's std::remove_if (+erase)

@mmmmmmmm 2009-05-17 18:01:45

To delete a single element, you could do:

std::vector<int> vec;


// Deletes the second element (vec[1])
vec.erase(vec.begin() + 1);

Or, to delete more than one element at once:

// Deletes the second through third elements (vec[1], vec[2])
vec.erase(vec.begin() + 1, vec.begin() + 3);

@bobobobo 2013-03-14 23:35:02

Note also binary operator+ is not necessarily defined for iterators on other container types, like list<T>::iterator (you cannot do list.begin() + 2 on an std::list, you have to use std::advance for that)

@Karl Morrison 2014-09-19 07:38:00

are you stating that the "+1" is the first element myVector[0] or the actual position myVector[1]

@Nick 2016-04-12 06:22:12

it+1 is element with id 1, e.g container[1]. first element is +0. See the comment below...

@dani 2016-10-05 20:36:33

With advance you must save the iterator in a variable. If you use std::next you can do it in one line: vec.erase( next(begin(vec), 123) );

@Pierre 2018-01-28 18:35:36

Thank you to all who have answered. What are we to think of a class design when such a simple operation as deleting an element, requires one to come to StackOverflow?

@user25 2018-04-10 11:58:58

what is begin()?, why not just 1?

@Force Gaia 2018-06-11 14:14:09

@user25 erase takes in a vector<T>::iterator, not an int. begin() is the itterator at the start of the vector, or element [0]. By adding to it, we increment it by the number of elements required to find the element we want to remove.

@Caleth 2018-07-03 09:38:05

@Pierre because the numerical index of a particular element is not the primary model of access, iterator is. All the functions that look at elements of a container use that container's iterators. E.g. std::find_if

@CodeBuddy 2009-05-17 18:08:55

The erase method on std::vector is overloaded, so it's probably clearer to call

vec.erase(vec.begin() + index);

when you only want to erase a single element.

@alap 2014-01-20 10:10:25

This is not good if you have only one element don't check the index...

@Zyx 2000 2014-09-01 09:32:19

But that problem appears no matter how many elements you have.

@Anne Quinn 2015-01-27 18:28:51

if there's only one element, index is 0, and so you get vec.begin() which is valid.

@qrtLs 2016-02-15 20:19:40

I wish someone would have mentioned that vec.erase(0) does not work, but vec.erase(vec.begin()+0) (or without +0) does. Otherwise I get no matching function call, which is why I came here

@Max 2011-03-10 20:47:43

template <typename T>
void remove(std::vector<T>& vec, size_t pos)
    std::vector<T>::iterator it = vec.begin();
    std::advance(it, pos);

@user1664047 2012-09-11 20:50:55

Max, what makes that function better than: template <typename T> void remove(std::vector<T>& vec, size_t pos) { vec.erase(vec.begin + pos); } I'm not saying either is better, merely asking out of personal interest and to return the best result this question could get.

@Lily Ballard 2012-09-11 21:28:26

@JoeyvG: Since a vector<T>::iterator is a random-access iterator, your version is fine and maybe a bit clearer. But the version that Max posted should work just fine if you change the container to another one that doesn't support random-access iterators

@Bim 2016-12-23 18:27:43

This is imo the better answer, as it applies to other container formats too. You could also use std::next().

Related Questions

Sponsored Content

25 Answered Questions

[SOLVED] What is the easiest way to initialize a std::vector with hardcoded elements?

7 Answered Questions

18 Answered Questions

[SOLVED] How to find out if an item is present in a std::vector?

  • 2009-02-20 21:58:41
  • Joan Venge
  • 836998 View
  • 565 Score
  • 18 Answer
  • Tags:   c++ vector std

18 Answered Questions

[SOLVED] Concatenating two std::vectors

16 Answered Questions

[SOLVED] Iteration over std::vector: unsigned vs signed index variable

4 Answered Questions

[SOLVED] C++ Erase vector element by value rather than by position?

5 Answered Questions

[SOLVED] C++ STL Vectors: Get iterator from index?

4 Answered Questions

[SOLVED] Erasing elements from a vector

  • 2008-12-07 10:10:20
  • Naveen
  • 124020 View
  • 88 Score
  • 4 Answer
  • Tags:   c++ vector stl erase

3 Answered Questions

[SOLVED] check if a std::vector contains a certain object?

  • 2010-08-10 15:52:47
  • jmasterx
  • 380560 View
  • 229 Score
  • 3 Answer
  • Tags:   c++ vector

4 Answered Questions

[SOLVED] Appending a vector to a vector

  • 2010-03-31 09:33:02
  • sub
  • 459378 View
  • 588 Score
  • 4 Answer
  • Tags:   c++ stl vector

Sponsored Content