C++ example

How to remove an element from a vector in C++

7 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

By index: v.erase(v.begin() + i), because erase takes an iterator, not a number. By value, in C++20: std::erase(v, value) removes every match, and std::erase_if(v, pred) removes every element the predicate accepts. Before C++20, use the erase-remove idiom: v.erase(std::remove(v.begin(), v.end(), value), v.end()).

std::vector has no remove(index) or remove(value) member, and the algorithm called std::remove does not change the vector's size, which is why this is one of the most-asked C++ questions. The sections below cover erasing by index, removing by value with the C++20 free functions, the older erase-remove idiom and its classic bug, erasing inside a loop without using an invalid iterator, and removing in constant time when the order does not matter, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1By index: v.erase(v.begin() + i)Recommended

erase takes an iterator to the element, so turn an index into one by adding it to begin() (std::next(v.begin(), i) is the same thing). Everything after the erased element shifts down by one, so the order is kept. Two iterators remove a half-open range [first, last), and pop_back() removes the last element. erase does not check the index: erasing end() or anything past it is undefined behaviour, so test i < v.size() first.

erase_index.cpp
#include <iostream>
#include <string>
#include <vector>

void print(const std::vector<std::string>& v) {
    std::cout << v.size() << ':';
    for (const auto& s : v) {
        std::cout << ' ' << s;
    }
    std::cout << '\n';
}

int main() {
    std::vector<std::string> v = {"a", "b", "c", "d", "e", "f"};

    // Remove index 2 ("c"): erase takes an iterator, so add i to begin()
    v.erase(v.begin() + 2);
    print(v);

    // erase returns an iterator to the element that moved into the gap
    auto next = v.erase(v.begin());
    std::cout << "after erasing the first: " << *next << '\n';
    print(v);

    // A range [first, last): removes indexes 1 and 2, not 3
    v.erase(v.begin() + 1, v.begin() + 3);
    print(v);

    // The last element: pop_back is the short way
    v.pop_back();
    print(v);

    // Check the index first: erasing at or past end() is undefined behaviour
    std::size_t i = 5;
    if (i < v.size()) {
        v.erase(v.begin() + i);
    } else {
        std::cout << "index " << i << " is out of range, size " << v.size() << '\n';
    }

    // Erasing destroys elements but keeps the memory
    std::vector<int> nums(100, 7);
    nums.erase(nums.begin() + 10, nums.end());
    std::cout << "size " << nums.size() << ", capacity " << nums.capacity() << '\n';
    // A request the library may ignore; libstdc++ honours it
    nums.shrink_to_fit();
    std::cout << "after shrink_to_fit: capacity " << nums.capacity() << '\n';
}

Output

Erasing index 2 of a b c d e f leaves 5: a b d e f. The iterator erase returns points at the element that slid into the gap, here after erasing the first: b; that return value is what makes erasing in a loop safe (section 4). The range begin() + 1 to begin() + 3 removes two elements, giving 2: b f. Erasing never gives memory back: after cutting 100 ints down to 10 the vector prints size 10, capacity 100, and only shrink_to_fit() brings it to capacity 10. That call is a non-binding request; GCC's library honours it.

2By value: std::erase and std::erase_if (C++20)

C++20 added two free functions that do the whole job in one call: std::erase(v, value) removes every element equal to value, and std::erase_if(v, pred) removes every element for which the predicate returns true. Both keep the order of the rest, run in one pass and return how many elements they removed. They remove all matches; to remove only the first, find it with std::find and erase that one position.

erase_value.cpp
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

void print(const std::vector<int>& v) {
    std::cout << v.size() << ':';
    for (int n : v) {
        std::cout << ' ' << n;
    }
    std::cout << '\n';
}

struct User {
    std::string name;
    bool active;
};

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};

    // C++20: remove every element equal to 5; returns how many went
    auto removed = std::erase(v, 5);
    std::cout << "removed " << removed << " -> ";
    print(v);

    // Every element that matches a condition: here the even numbers
    removed = std::erase_if(v, [](int n) { return n % 2 == 0; });
    std::cout << "removed " << removed << " -> ";
    print(v);

    // Only the FIRST match: find it, then erase that one position
    auto it = std::find(v.begin(), v.end(), 1);
    if (it != v.end()) {
        v.erase(it);
    }
    std::cout << "first 1 gone -> ";
    print(v);

    // A value that is not there is no error: nothing is removed
    std::cout << "removed " << std::erase(v, 42) << '\n';

    // Objects: test a member in the predicate
    std::vector<User> users = {{"ada", true}, {"bob", false}, {"cy", true}};
    std::erase_if(users, [](const User& u) { return !u.active; });
    std::cout << "users:";
    for (const auto& u : users) {
        std::cout << ' ' << u.name;
    }
    std::cout << '\n';
}

Output

The three 5s go in one call (removed 3 -> 8: 3 1 4 1 9 2 6 3), then the even numbers (removed 3 -> 5: 3 1 1 9 3). The std::find version removes only the first 1: first 1 gone -> 4: 3 1 9 3. A value that is not in the vector is not an error, std::erase just reports removed 0. For objects, put the test in the lambda, which leaves users: ada cy. To check for a value without removing it, see checking if a vector contains an element.

3Before C++20: the erase-remove idiom

std::remove and std::remove_if come from <algorithm> and work on any iterator range, so they cannot change a container's size. They move the elements you keep to the front and return an iterator to the new logical end; what is left after it is junk. You then erase from that iterator to end(). That pair is the erase-remove idiom, and it is exactly what std::erase does for you in C++20.

erase_remove.cpp
#include <algorithm>
#include <iostream>
#include <vector>

void print(const std::vector<int>& v) {
    std::cout << v.size() << ':';
    for (int n : v) {
        std::cout << ' ' << n;
    }
    std::cout << '\n';
}

int main() {
    std::vector<int> v = {1, 2, 3, 2, 4, 2};

    // std::remove shifts the kept elements to the front and returns the
    // new logical end. It only has iterators, so it cannot shrink the vector
    auto new_end = std::remove(v.begin(), v.end(), 2);
    std::cout << "kept " << (new_end - v.begin()) << ", size still " << v.size() << '\n';

    // erase then cuts off the leftover tail: the erase-remove idiom
    v.erase(new_end, v.end());
    print(v);

    // The usual one-liner, with a condition (remove_if) this time
    std::vector<int> w = {5, 12, 7, 30, 8};
    w.erase(std::remove_if(w.begin(), w.end(), [](int n) { return n > 10; }), w.end());
    print(w);

    // C++20 ranges: std::ranges::remove returns the tail to erase
    std::vector<int> x = {0, 1, 0, 2, 0};
    auto tail = std::ranges::remove(x, 0);
    x.erase(tail.begin(), tail.end());
    print(x);

    // Gotcha: forgetting the second argument erases ONE element
    // (the first of the tail), so the vector keeps the rest of the junk
    std::vector<int> y = {1, 2, 3, 2, 2};
    y.erase(std::remove(y.begin(), y.end(), 2));
    std::cout << "size " << y.size() << ", expected 2\n";
}

Output

After std::remove alone the program prints kept 3, size still 6: the three kept values are at the front, but the vector has not shrunk, and the values in the tail are unspecified. The erase call cuts it to 3: 1 3 4. The last block is the bug people hit most: v.erase(it) with one argument erases a single element, so removing three 2s from five elements leaves size 4, expected 2, with junk in it. Always pass v.end() as the second argument. Use std::remove from <algorithm>, not the remove in <cstdio>, which deletes a file.

4Erasing inside a loop

erase invalidates the iterator you passed and every iterator and reference after it, including end(). A loop that calls v.erase(it) and then ++it uses a dead iterator, which is undefined behaviour: it may skip elements, run off the end or crash. Assign the iterator that erase returns, and advance only when nothing was erased. A range-based for hides its iterator, so it cannot erase at all. If all you need is a condition, std::erase_if does the same in one pass instead of shifting the tail once per removed element.

erase_in_loop.cpp
#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    // erase invalidates `it`, but returns the next valid iterator:
    // take that one, and only ++it when nothing was erased
    for (auto it = v.begin(); it != v.end();) {
        if (*it % 3 == 0) {
            std::cout << "erasing " << *it << '\n';
            it = v.erase(it);
        } else {
            ++it;
        }
    }
    std::cout << "left:";
    for (int n : v) {
        std::cout << ' ' << n;
    }
    std::cout << '\n';

    // With indexes: do not advance after an erase, the next element
    // has just moved into position i
    std::vector<int> w = {4, 4, 5, 4, 6};
    for (std::size_t i = 0; i < w.size();) {
        if (w[i] == 4) {
            w.erase(w.begin() + i);
        } else {
            ++i;
        }
    }
    std::cout << "w: " << w.size() << " left, first " << w.front() << '\n';

    // Several indexes at once: erase from the highest down, so the
    // lower indexes still name the same elements
    std::vector<char> letters = {'a', 'b', 'c', 'd', 'e', 'f'};
    std::vector<std::size_t> drop = {1, 4, 2};
    std::ranges::sort(drop, std::greater{});
    for (std::size_t i : drop) {
        letters.erase(letters.begin() + i);
    }
    std::cout << std::string(letters.begin(), letters.end()) << '\n';
}

Output

The iterator loop removes 3, 6 and 9 and leaves left: 1 2 4 5 7 8. The index loop has the same rule in another form: after w.erase(w.begin() + i) the next element is now at i, so i stays put, and the adjacent 4s are both removed (w: 2 left, first 5). To drop several known indexes, erase from the highest down; erasing index 1 first would shift the elements that indexes 2 and 4 refer to. Sorted descending, removing 1, 4 and 2 from abcdef leaves adf.

5Fast removal when order does not matter: swap and pop

erase keeps the order by moving every later element down one slot, so removing near the front of a big vector costs time proportional to its size. When the order does not matter (a list of particles, open connections, pending jobs), move the last element into the hole and pop_back(): one move, whatever the size. The Item type below counts its moves so you can see the difference.

swap_and_pop.cpp
#include <iostream>
#include <string>
#include <utility>
#include <vector>

// O(1) removal when the order does not matter: move the last element
// into the hole, then drop the last slot
template <typename T>
void unordered_erase(std::vector<T>& v, std::size_t i) {
    if (i + 1 != v.size()) {
        v[i] = std::move(v.back());
    }
    v.pop_back();
}

// Counts how often elements are moved, to show what erase costs
struct Item {
    static inline int moves = 0;
    int id = 0;
    Item() = default;
    Item(const Item&) = default;
    Item& operator=(Item&& other) noexcept {
        id = other.id;
        ++moves;
        return *this;
    }
};

int main() {
    std::vector<std::string> names = {"ann", "ben", "cat", "dan", "eve"};
    unordered_erase(names, 1);  // "eve" takes ben's place
    std::cout << names.size() << ':';
    for (const auto& n : names) {
        std::cout << ' ' << n;
    }
    std::cout << '\n';

    std::vector<Item> items(1000);

    // erase at the front shifts every later element down by one
    Item::moves = 0;
    items.erase(items.begin());
    std::cout << "erase(begin()): " << Item::moves << " moves\n";

    // swap-and-pop moves one element whatever the size
    Item::moves = 0;
    unordered_erase(items, 0);
    std::cout << "unordered_erase: " << Item::moves << " move\n";
}

Output

Removing ben moves eve into its place: 4: ann eve cat dan. On 1000 elements, erase(begin()) costs 999 moves and the swap-and-pop version 1 move. The i + 1 != v.size() test skips moving the last element onto itself, and the function, like erase, must not be called with an index past the end. If you remove from the front all the time, a std::deque erases at either end in constant time.

6Which should you use?

MethodRemovesKeeps orderStandard
v.erase(v.begin() + i)One element by indexYesAny
v.erase(first, last)A range of indexesYesAny
v.pop_back()The last elementYesAny
std::erase(v, value)Every match, one passYesC++20
std::erase_if(v, pred)Every element pred acceptsYesC++20
v.erase(std::find(...))The first match onlyYesAny; check for end() first
v.erase(std::remove(...), v.end())Every match, one passYesBefore C++20
v[i] = std::move(v.back()); v.pop_back();One element in O(1)NoAny

Frequently asked questions

Why does std::remove not change the size of my vector?

std::remove is an algorithm that only sees iterators, not the container, so it cannot shrink anything. It moves the elements you keep to the front and returns the new logical end; the elements after it are left in an unspecified state. Pass that iterator to v.erase(new_end, v.end()) to actually remove them, or use std::erase(v, value) in C++20, which does both steps.

Does erasing from a vector free memory?

No. erase, pop_back and clear destroy the elements but keep the allocation, so capacity() stays the same: cutting 100 ints to 10 prints size 10, capacity 100. Call v.shrink_to_fit() to ask for the spare memory back (GCC honours it, but the standard allows it to do nothing), or swap with a fresh copy: std::vector<int>(v).swap(v).

Can I erase from a vector inside a range-based for loop?

No. The range-based for keeps its own iterator, and erase invalidates it and everything after it, so the next step of the loop is undefined behaviour. Use std::erase_if(v, pred), or an explicit iterator loop that does it = v.erase(it); when it erases and ++it only when it does not.

How do I remove duplicates from a vector in C++?

If the order can change, sort first and then erase what std::unique leaves behind: std::sort(v.begin(), v.end()); v.erase(std::unique(v.begin(), v.end()), v.end());. std::unique only removes adjacent duplicates, which is why the sort comes first, and like std::remove it does not shrink the vector by itself. To keep the first occurrence of each value in the original order, track seen values in a std::set or std::unordered_set and use std::erase_if.

Does erase delete the object a pointer in the vector points to?

erase destroys the element, and for a raw pointer that destroys only the pointer, not the object it points to, so std::vector<Widget*> leaks unless you delete it first. Store std::unique_ptr<Widget> instead: erasing the unique_ptr deletes the object for you, and std::erase_if works on it unchanged.

Which iterators does vector::erase invalidate?

Every iterator, pointer and reference at or after the erased position, including end(). Those before it stay valid, because erasing never reallocates. That is why erase returns an iterator to the element after the removed ones, and why several indexes are erased from the highest down.

Run it yourself

Open any of these in the full C++ editor to tweak, run and share.

C++ playground