是否有一个函数可以从向量中删除一个元素而不用在 c++ stdlib 中移动它?
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++标准库中有不会移动元素的函数吗?比如把后面的元素放在被移除的元素上然后弹回来?
没有内置任何东西,但自己动手做起来很简单。
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 中,您可以使用 std::optional
s 的向量和范围库
对其进行建模
#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';
}
如果我用vector.erase()
比如
std::vector<int> n = { 3, 5, 6, 7 };
n.erase(n.begin() + 1);
vector
将删除元素后的所有元素向下移动。
C++标准库中有不会移动元素的函数吗?比如把后面的元素放在被移除的元素上然后弹回来?
没有内置任何东西,但自己动手做起来很简单。
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 中,您可以使用 std::optional
s 的向量和范围库
#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';
}