简体   繁体   English

迭代器是否支持+运算符?

[英]Does iterator support + operator?

I saw the following code used to delete one selected element from std::vector : 我看到以下代码用于从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. 但是,我不确定此代码是否遵循C ++ STL标准。

To make this code generic, so it works no matter whether the iterator supports operator + , and uses the most efficient available implementation: 要使此代码具有通用性,所以无论迭代器是否支持operator + ,它都可以工作,并使用最有效的可用实现:

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. 在内部,如果迭代器类型支持, std::advance使用operator + 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::list<>::iterator )它会在循环中一次一步地前进迭代器,就像你发布的第一个代码一样。

随机访问迭代器支持加法和减法,而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). 对于其他一些容器类型(例如deque或map),这同样不适用。

So, your code is better for a vector, but the other code may have been intended to work with other types of container. 因此,对于向量,您的代码更好,但其他代码可能已用于其他类型的容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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