简体   繁体   English

是否有 function 从向量中删除元素而不在 c++ 标准库中移动它?

[英]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如果我使用vector.erase()例如

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

vector will shift all the elements after the element removed down. vector将删除元素后的所有元素向下移动。

Is there a function in the C++ standard library that will not shift the elements? C++ 标准库中是否存在不会移动元素的 function? 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如果您不想移动任何元素,那么在 C++20 中,您可以 model 使用std::optional的向量和范围库

#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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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