-3

I want to erase elements by indexes. Inside eraseIndexs function I access to begin & end iterators.When I create a vector from begin and end iterators create a new vector from them.

How to erase elements by iterators?

template <typename ForwardIt>
void eraseIndexs(ForwardIt& begin, ForwardIt& end, const vector<size_t>& indexs){
    using T = typename iterator_traits<ForwardIt>::value_type;
    vector<T> v(begin, end);
    for (size_t index = 0; index < indexs.size(); index++)
        v.erase(v.begin() + indexs[index] - index);
}
Mostafa Sataki
  • 305
  • 3
  • 11

1 Answers1

2

You are not erasing anything

you are making a local std:vector in your function :

vector<T> v(begin, end);

and then erasing from it

v.erase(v.begin() + indexs[index] - index);

It doesn't erase your real vector's iterator .

If you want to erase from vector :

you have to pass std::vector to your function and use erase member function :

template <typename Container>
void eraseIndexs(Container& c, const vector<size_t>& indexs){
    for (size_t index = 0; index < indexs.size(); index++)
        c.erase(c.begin() + indexs[index] - index);
}
uchar
  • 2,552
  • 4
  • 29
  • 50