一个接一个地从向量中删除元素是非常低效的。这是因为对于每次擦除,它必须将所有元素向下复制一个,然后重新分配一个更小的向量。
相反,请使用擦除删除成语。此过程将通过移动后面的项目以替换较早的项目来删除项目(它保持原始顺序)。删除项目后,它将执行一次擦除(这只是列表的末尾)以重新分配一个新的向量,该向量比 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