簡體   English   中英

是否有 function 從向量中刪除元素而不在 c++ 標准庫中移動它?

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

如果我使用vector.erase()例如

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

vector將刪除元素后的所有元素向下移動。

C++ 標准庫中是否存在不會移動元素的 function? 就像把后元素放在被移除的元素上然后彈回來?

沒有任何內置的東西,但自己做是微不足道的。

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.

如果您不想移動任何元素,那么在 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