是否存在标准可变参数函数可批量删除std::vector指定索引的元素?
问题解答
C++标准库并没有提供支持直接传入任意数量索引参数的vector::erase重载,没法直接用v.erase(0, 1, 3)这种方式调用。不过可以通过以下几种实用方法实现需求:
方法一:按从大到小的顺序删除索引
vector删除元素后,后续元素会前移导致索引偏移,从最大的索引开始删除就能避免这个问题:
#include <vector> #include <algorithm> std::vector<int> v = {1, 2, 3, 4, 5}; std::vector<size_t> indices = {0, 1, 3}; // 把索引按降序排序 std::sort(indices.rbegin(), indices.rend()); for (size_t idx : indices) { if (idx < v.size()) { // 防止索引越界 v.erase(v.begin() + idx); } } // 最终v的值为 {3, 5}
方法二:结合std::remove_if筛选保留元素
通过标记需要删除的索引,用remove_if把要保留的元素移到容器前端,再用erase清理尾部无效元素:
#include <vector> #include <algorithm> #include <unordered_set> std::vector<int> v = {1, 2, 3, 4, 5}; const std::unordered_set<size_t> to_remove = {0, 1, 3}; size_t current_idx = 0; v.erase( std::remove_if(v.begin(), v.end(), [&](const int&) { return to_remove.count(current_idx++); }), v.end() ); // 最终v的值为 {3, 5}
方法三:封装自定义函数实现类似调用方式
用可变参数模板封装一个函数,内部处理索引排序和删除逻辑,就能实现用户想要的简洁调用:
#include <vector> #include <algorithm> #include <cstddef> template<typename T, typename... IdxTypes> void erase_indices(std::vector<T>& vec, IdxTypes... indices) { std::vector<size_t> idx_list = {static_cast<size_t>(indices)...}; std::sort(idx_list.rbegin(), idx_list.rend()); for (size_t idx : idx_list) { if (idx < vec.size()) { vec.erase(vec.begin() + idx); } } } // 调用示例 std::vector<int> v = {1, 2, 3, 4, 5}; erase_indices(v, 0, 1, 3); // 直接传入多个索引参数
内容的提问来源于stack exchange,提问作者TwistedBlizzard
相关产品推荐
相关产品推荐

