简体   繁体   中英

Is there a function to remove an element from a vector without shifting it in the c++ stdlib?

If I use vector.erase() such as

std::vector<int> n = { 3, 5, 6, 7 };
n.erase(n.begin() + 1);

vector will shift all the elements after the element removed down.

Is there a function in the C++ standard library that will not shift the elements? Like putting the back element at the removed element and pop back?

There isn't anything built in, but it's trivial to do yourself.

std::vector<int> n = { 3, 5, 6, 7 }; // create vector
n[1] = std::move(n.back());          // move last element to removal location
n.pop_back();                        // remove unneeded element.

If you don't want to shift any elements, then in C++20 you can model this with a vector of std::optional s and the ranges library

#include <cstddef>
#include <optional>
#include <ranges>
#include <vector>

template<typename T>
auto remove_element(std::vector<std::optional<T>> &v, size_t i) {
    v[i] = std::nullopt;

    return v
        | std::views::filter(&std::optional<T>::has_value)
        | std::views::transform([](auto &&o) {return *o;});
}

#include <iostream>

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

    for (int i : remove_element(v, 3))
        cout << i << ','; // 1,2,3,5,6,

    cout << '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM