简体   繁体   English

如何检查简单的C ++标准库迭代器是否可以高级?

[英]How to check if simple C++ standard library iterator can be advanced?

Suppose I have a class encapsulating std container: 假设我有一个封装std容器的类:

class Stash
{
    list<int> Data;

public:
    list<int>::const_iterator GetAccess() const { return Data.begin(); }
};

It's very convenient way of forcing the user to read the data in form of the iterator. 这是强制用户以迭代器形式读取数据的非常方便的方法。 However, I can't find the way other that comparing the iterator to container.end() . 但是,除了将迭代器与container.end()比较之外,我找不到其他方法。 So, I would like to know if there's an option to do it solely by stdlib or I have to write iterator class myself (with can_advance method, for example). 因此,我想知道是否可以通过stdlib单独执行此操作,或者我必须自己编写迭代器类(例如,使用can_advance方法)。

Relevant question might be this one , but it asks whether the iterator is valid , not whether it can advance . 相关的问题可能是这个 ,但它询问迭代器是否有效 ,而不是是否可以进行迭代。 I weren't able to find any information about the latter. 我找不到有关后者的任何信息。

You can't do this, a single iterator does not contain the information when it is at the end of the sequence its pointing into. 您无法执行此操作,当单个迭代器位于指向其的序列的末尾时,该迭代器将不包含该信息。

Normally, this is solved by either providing a range (think std::make_pair(cont.begin(), cont.end()) ), or providing begin() and end() methods to your class, effectively making it a range. 通常,可以通过提供一个范围(考虑一下std::make_pair(cont.begin(), cont.end()) )或为您的类提供begin()end()方法来有效地解决这个问题,从而有效地使其成为一个范围。

Iterators work in pairs: an iterator that points to the beginning of a sequence and an iterator that points past the end of the sequence. 迭代器是成对工作的:指向序列开头的迭代器和指向序列结尾的迭代器。 That's why all the containers have begin() and end() member functions: so you can look at the sequence of values that the container manages. 这就是为什么所有容器都具有begin()end()成员函数的原因:因此,您可以查看容器管理的值的顺序。

It would be far more idiomatic to change the name of GetAccess to begin and to add end . GetAccess的名称更改为begin并添加end会更加习惯。 Having end() would also make it possible to apply standard algorithms to the data. 使用end()还可以将标准算法应用于数据。

What you seem to be asking for is a "lookahead" iterator. 您似乎想要的是一个“超前”迭代器。 You could write a class to "adapt" an iterator to have lookahead, where the adaptor just stays one step ahead of your code: 您可以编写一个类来“适应”迭代器以使其具有超前性,其中适配器仅比代码领先一步:

template<class FwdIter>
class lookahead_iterator
{
public:
    lookahead_iterator(const FwdIter& begin): cur_iter(begin), next_iter(++begin) {}
    operator FwdIter() const { return cur_iter; }
    lookahead_iterator<FwdIter>& operator ++() { cur_iter = next_iter++; return *this; }
    // Other methods as needed.
private:
    FwdIter cur_iter;
    FwdIter next_iter;
};

Needless to say, this gets a lot more complicated if you need more than a forward iterator. 不用说,如果您需要的不仅仅是正向迭代器,这将变得更加复杂。

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

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