比较C++中的迭代器

comparing iterators in C++

本文关键字:迭代器 C++ 比较      更新时间:2023-10-16

我对比较C++中的迭代器感到困惑。带有以下代码:

std::iterator< std::forward_iterator_tag, CP_FileSystemSpec> Iter1;
std::iterator< std::forward_iterator_tag, CP_FileSystemSpec> Iter2;
while( ++Iter1 != Iter2 )
{
}

错误为:

error: no match for 'operator++' in '++Iter1'

我似乎还记得,你不能做上面代码正在做的事情。但我不太知道如何进行比较。

std::iterator本身不是迭代器,而是其他迭代器可以继承的基类,以获得一些标准的typedef。

template<class Category, class T, class Distance = ptrdiff_t, class Pointer = T*, class Reference = T&> 
struct iterator 
{ 
    typedef T value_type; 
    typedef Distance difference_type; 
    typedef Pointer pointer; 
    typedef Reference reference; 
    typedef Category iterator_category; 
};

这个错误与比较无关——它告诉您特定的迭代器不支持递增。

您应该从std::iterator派生——直接实例化它毫无意义。

要使该示例工作,请使用由序列支持的迭代器,例如vector:

std::vector<int> foo(10); // 10 times 0
std::vector<int>::iterator it1 = foo.begin();
std::vector<int>::iterator it2 = foo.end();
while(++it1 != it2) {
    // do stuff
}

请注意,这不是迭代集合的规范方式。它也很棘手,因为它跳过了序列的第一个元素。使用此:

for(std::vector<int>::iterator it = foo.begin(); it != foo.end(); it++) {
    // do stuff
}