通过索引删除一组元素
Deleting a bunch of elements by their index?
我有一个
vector<int> myVector;
我有一个index
列表要删除:
vector<size_t> deleteIndex;
哪种策略最有效地删除这些索引?
实际上一个不有效的解决方案是:
//> sort deleteindex
auto deleted= 0;
for(auto i=0;i<deleteIndex.size();i++ {
myVector.erase(myVector.begin()+deleteIndex[i]-deleted);
deleted++;
}
逐个从vector中擦除元素是非常低效的。这是因为对于每次擦除,必须将所有元素向下复制1,然后重新分配一个小1的向量。
应该使用擦除-删除习语。这个过程将通过移动后面的项来替换前面的项来删除项(它保持原始顺序)。在元素被删除后,它将执行一次擦除(这只是列表的末尾)来重新分配一个新向量,该向量小于n个元素(其中n是被删除的元素数)。
样本实现:template <class _FwdIt, class _FwdIt2>
_FwdIt remove_by_index(_FwdIt first,
_FwdIt last,
_FwdIt2 sortedIndexFirst,
_FwdIt2 sortedIndexLast)
{
_FwdIt copyFrom = first;
_FwdIt copyTo = first;
_FwdIt2 currentIndex = sortedIndexFirst;
size_t index = 0;
for (; copyFrom != last; ++copyFrom, ++index)
{
if (currentIndex != sortedIndexLast &&
index == *currentIndex)
{
// Should delete this item, so don't increment copyTo
++currentIndex;
print("%d", *copyFrom);
}
else
{
// Copy the values if we're at different locations
if (copyFrom != copyTo)
*copyTo = *copyFrom;
++copyTo;
}
}
return copyTo;
}
示例用法:#include <vector>
#include <algorithm>
#include <functional>
int main(int argc, char* argv[])
{
std::vector<int> myVector;
for (int i = 0; i < 10; ++i)
myVector.push_back(i * 10);
std::vector<size_t> deleteIndex;
deleteIndex.push_back(3);
deleteIndex.push_back(6);
myVector.erase(
remove_by_index(myVector.begin(), myVector.end(), deleteIndex.begin(), deleteIndex.end()),
myVector.end());
for (std::vector<int>::iterator it = myVector.begin();
it != myVector.end(); ++it)
{
printf("%d ", *it);
}
return 0;
}
要点:https://gist.github.com/eleven41/5746079
测试在这里:http://ideone.com/0qkDw5
如果允许对myVector
重新排序,则只需遍历要删除的项,通过与最后一个元素交换并弹出它来删除它们。
如果您需要保持顺序,对deleteIndex
容器进行排序,并通过移动其他元素来执行单个有序传递以删除元素。
相关文章:
- 经过最后一个数组元素末尾的指针是否应该等于超过整个数组末尾的指针?
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何通过查找迭代器结果分配给一组对的元素
- 在删除之前更新一组元素指针中的元素
- 无法在STL中打印一组矢量的元素
- 迭代一组和擦除元素
- 最长的子序列,其元素构成一组递增的整数
- 如何查找一组类型对是否包含一个元素作为第二个成员
- 将大于k的数组元素导入到另一个数组C 中
- 如何访问一组对元素的图
- 如何在对一组中的一对之间找到一个元素
- 如何创建一组UI元素,您可以迭代
- 组合两个数组元素或将一个数组元素分发到另一个数组元素
- 一组结构缺少元素
- 基于权重在N个桶之间分配一组元素
- 按一对数组元素的和对向量进行排序
- 对于一组不断添加和删除的元素,我应该使用哪个容器
- 查找一组元素的位置
- 通过索引删除一组元素
- 将一组元素分解成最少数量的回文