fork download
  1. #include <vector>
  2. #include <algorithm>
  3. #include <functional>
  4.  
  5. template <class _FwdIt, class _FwdIt2>
  6. _FwdIt remove_by_index(_FwdIt first,
  7. _FwdIt last,
  8. _FwdIt2 sortedIndexFirst,
  9. _FwdIt2 sortedIndexLast)
  10. {
  11. _FwdIt copyFrom = first;
  12. _FwdIt copyTo = first;
  13. _FwdIt2 currentIndex = sortedIndexFirst;
  14.  
  15. size_t index = 0;
  16. for (; copyFrom != last; ++copyFrom, ++index)
  17. {
  18. if (currentIndex != sortedIndexLast &&
  19. index == *currentIndex)
  20. {
  21. // Should not delete this item, so don't increment copyTo
  22. ++currentIndex;
  23. }
  24. else
  25. {
  26. // Copy the values if we're at different locations
  27. if (copyFrom != copyTo)
  28. *copyTo = *copyFrom;
  29. ++copyTo;
  30. }
  31. }
  32. return copyTo;
  33. }
  34.  
  35. int main(int argc, char* argv[])
  36. {
  37. std::vector<int> myVector;
  38.  
  39. for (int i = 0; i < 10; ++i)
  40. myVector.push_back(i * 10);
  41.  
  42. std::vector<size_t> deleteIndex;
  43. deleteIndex.push_back(3);
  44. deleteIndex.push_back(6);
  45.  
  46. myVector.erase(
  47. remove_by_index(myVector.begin(), myVector.end(), deleteIndex.begin(), deleteIndex.end()),
  48. myVector.end());
  49.  
  50. for (std::vector<int>::iterator it = myVector.begin();
  51. it != myVector.end(); ++it)
  52. {
  53. printf("%d ", *it);
  54. }
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
0 10 20 40 50 70 80 90