Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does iterator support + operator?

Tags:

c++

stl

I saw the following code used to delete one selected element from std::vector:

vector<hgCoord>::iterator it;
int iIndex = 0;
    const int iSelected = 5;
for( it = vecPoints.begin(); it != vecPoints.end(); ++it, ++iIndex )
{
    if( iIndex == iSelected )
    {
        vecPoints.erase( it );
        break;
    }
}

I argue that this code is not efficient and should be written as follows:

vector<hgCoord>::iterator it;
int iIndex = 0;
    const int iSelected = 5; // we assume the vector has more than 5 elements.

    vecPoints.erase( vecPoints.begin() + iSelected );

However, I am not sure whether or not this code is following the C++ STL standard.

like image 853
q0987 Avatar asked Nov 04 '10 19:11

q0987


4 Answers

To make this code generic, so it works no matter whether the iterator supports operator +, and uses the most efficient available implementation:

template <typename C>
void erase_at(C& container, typename C::size_type index) {
    typename C::iterator i = container.begin();
    std::advance(i, index);
    container.erase(i);
}

Internally, std::advance uses operator + if the iterator type supports it. Otherwise (e.g. for std::list<>::iterator) it advances the iterator one step at a time in a loop, just like the first code you posted.

like image 132
Konrad Rudolph Avatar answered Nov 13 '22 10:11

Konrad Rudolph


Random-access iterators support addition and subtraction, and std::vector iterators are random-access.

like image 21
John Calsbeek Avatar answered Nov 13 '22 10:11

John Calsbeek


You argue correctly :)

like image 28
Armen Tsirunyan Avatar answered Nov 13 '22 09:11

Armen Tsirunyan


That should work fine for a vector because vector iterators are random access iterators, so it's OK to add an offset as you have done. The same won't work for some other container types (such as deque or map).

So, your code is better for a vector, but the other code may have been intended to work with other types of container.

like image 27
dajames Avatar answered Nov 13 '22 09:11

dajames