Skip to content

Instantly share code, notes, and snippets.

@eleven41
Last active December 18, 2015 07:19
Show Gist options
  • Save eleven41/5746079 to your computer and use it in GitHub Desktop.
Save eleven41/5746079 to your computer and use it in GitHub Desktop.
remove_by_index STL function to remove items from a STL collection by index
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 not delete this item, so don't increment copyTo
++currentIndex;
}
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 _tmain(int argc, _TCHAR* 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)
{
_tprintf(_T("%d "), *it);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment