我可以写:
my_range | ranges::views::remove(3)
使用ranges-v3库,从范围my_range
中删除等于3的元素。这也可以在 C++20 中完成
my_range | std::views::filter([](auto const& val){ return val != 3; })
但是 - 如何删除 my_range
中位置 3 处的元素,并将元素保留在位置 0、1、2、4、5 等?
最佳答案
这是一种方法:
#include <iostream>
#include <ranges>
#include <range/v3/view/take.hpp>
#include <range/v3/view/drop.hpp>
#include <range/v3/view/concat.hpp>
int main() {
const auto my_range = { 10, 20, 30, 40, 50, 60, 70 };
auto index_to_drop = 3; // so drop the 40
auto earlier = my_range | ranges::views::take(index_to_drop - 1);
auto later = my_range | ranges::views::drop(index_to_drop);
auto both = ranges::views::concat(earlier, later);
for (auto const & num : both) { std::cout << num << ' '; }
}
这将产生:
10 20 30 50 60 70
...没有 40。
查看它正在运行 Godbolt 。但编译时间非常短。此外,concat()
不是 C++20 的一部分。也许在 C++23 中?
关于c++ - 如何删除一个范围内的第N个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68976564/