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

标签 c++ stl

我看到以下代码用于从 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;
    }
}

我认为这段代码效率不高,应该这样写:

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 );

但是,我不确定这段代码是否遵循 C++ STL 标准。

最佳答案

为了使这段代码通用,无论迭代器是否支持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);
}

在内部,std::advance使用 operator +如果迭代器类型支持它。否则(例如 std::list<>::iterator )它在循环中一次推进迭代器一步,就像您发布的第一个代码一样。

关于c++ - 迭代器是否支持+运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4100284/

相关文章:

c++ - 错误: sigjmp_buf does not name a type. When Compiling my project with Poco C++ libraries

algorithm - 在没有循环的情况下向向量的所有条目添加一个值

c++ - 排除外部错误 R6025 - 纯虚函数调用

c++ - 这在 C++ 中。它是如何工作的?

c++ - 如何使用 bind1st 和 bind2nd?

c++ - 为什么 += 对没有值的 std::map 键起作用?

c++ - map 给出错误的值

c++ - 在 vector 的 vector 上使用算法

java - JNI : passing integer array from Java to C

c++ - 如何将 "Dummy"值替换为 std::cin?