我有一个项目向量 items
,还有一个应该从 items
中删除的索引向量:
std::vector<T> items;
std::vector<size_t> indicesToDelete;
items.push_back(a);
items.push_back(b);
items.push_back(c);
items.push_back(d);
items.push_back(e);
indicesToDelete.push_back(3);
indicesToDelete.push_back(0);
indicesToDelete.push_back(1);
// given these 2 data structures, I want to remove items so it contains
// only c and e (deleting indices 3, 0, and 1)
// ???
知道每次删除都会影响到indicesToDelete中的所有其他索引,那么最好的删除方式是什么?
几个想法如下:
1. 逐个将items复制到一个新向量中,如果索引在indicesToDelete中则跳过。 2. 遍历items,对于每个删除操作,将indicesToDelete中大于该索引的所有项都减1。 3. 先对indicesToDelete进行排序,然后遍历indicesToDelete,对于每个删除操作,增加一个indexCorrection,从后续的索引中减去。
这些方法似乎过于复杂了。有更好的想法吗?
编辑:下面是解决方案,基本上是#1的变体,但使用迭代器定义要复制到结果的块。
template<typename T>
inline std::vector<T> erase_indices(const std::vector<T>& data, std::vector<size_t>& indicesToDelete/* can't assume copy elision, don't pass-by-value */)
{
if(indicesToDelete.empty())
return data;
std::vector<T> ret;
ret.reserve(data.size() - indicesToDelete.size());
std::sort(indicesToDelete.begin(), indicesToDelete.end());
// new we can assume there is at least 1 element to delete. copy blocks at a time.
std::vector<T>::const_iterator itBlockBegin = data.begin();
for(std::vector<size_t>::const_iterator it = indicesToDelete.begin(); it != indicesToDelete.end(); ++ it)
{
std::vector<T>::const_iterator itBlockEnd = data.begin() + *it;
if(itBlockBegin != itBlockEnd)
{
std::copy(itBlockBegin, itBlockEnd, std::back_inserter(ret));
}
itBlockBegin = itBlockEnd + 1;
}
// copy last block.
if(itBlockBegin != data.end())
{
std::copy(itBlockBegin, data.end(), std::back_inserter(ret));
}
return ret;
}
indeciesToDelete
进行排序,然后以相反的顺序删除它们。那样就不需要更正了。虽然,这仍然是缓慢的答案。” - Mooing Duckstd::string
和一些整数。通常我们会删除少量元素。我将使用下面发布的反向排序解决方案。谢谢大家。 - tenfourstd::copy(itBlockBegin, data.end(), std::back_inserter(ret));
。 - JohnPS