简体   繁体   中英

Does iterator support + operator?

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.

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 (eg for std::list<>::iterator ) it advances the iterator one step at a time in a loop, just like the first code you posted.

随机访问迭代器支持加法和减法,而std::vector迭代器是随机访问。

你正确争辩:)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM