我有一个项目向量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
?
有几个想法是:
- Copy
items
一次指向一个新向量,如果索引位于则跳过indicesToDelete
- Iterate
items
对于每次删除,减少中的所有项目indicesToDelete
哪个有更大的指数。
- Sort
indicesToDelete
首先,然后迭代indicesToDelete
,并且对于每个删除增加一个indexCorrection
从后续索引中减去它。
看来我是想太多了,这样一个看似微不足道的任务。还有更好的想法吗?
Edit这是解决方案,基本上是#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;
}