[英]Forward iterator with a moving end()
因此,我正在设计一个类(通过网络)连接到服务以接收一些数据的类。 我不知道我将如何预先接收人工数据点。 但是,我想知道,是否有一种方法可以使用forward_iterator使该类可迭代,以便充分享受STL的乐趣。 我的想法是这样的:
self_type operator++() {
// if there are some locally cached data points left return next
// else connect to service again to receive the next batch of data
}
但是,由于我不能提供有效的end()
,我很好奇,如果仍然可以做到这一点。
一个替代的(且无迭代器的)接口可能类似于:
bool hasMoreDataPoints() const;
DataPoint& getNext();
这显然不适用于任何STL算法。
像使用istream_iterator
的标准库一样进行操作:当数据用尽时,请设置迭代器状态,使其与该类型的默认构造对象进行比较。 然后是您的end()
等效项。
我想您可以在类中使用某种类型的存储来进行缓存,例如std::vector
。 然后,您可以仅公开其std::begin()
和std::end()
迭代器(以所有常用形式)。 然后,算法直接在基础容器上工作,并使用容器迭代器的成员函数,例如operator++
, operator==
等。
如果需要引入更多逻辑,则需要创建自定义迭代器。 这基本上可以通过组合来完成,即编写一个包含与您的存储容器相对应的迭代器的新类,并公开您所需的所有功能,同时进行相应的调整。
编辑:正如您所说的,您使用列表:
struct DataPoints
{
std::list<double> _list;
auto begin() const
{
return _list.begin();
}
auto end() const
{
return _list.end();
}
//other versions: non-const begin and end, cbegin, cend
}
简单的方法就已经足够了。 您可以将其用作普通列表:
DataPoints d;
std::find(d.begin(), d.end(), 10.0);
如前所述,如果您需要更多逻辑,则可能需要编写自定义迭代器。
但是,由于我不能提供有效的end(),我很好奇,如果仍然可以做到这一点 ...。
您可以使用STL随附的任何容器类。 假设您正在使用向量或列表或任何其他合适的容器。 只需使用STL提供的内容并编写自己的包装器
vector<datapoint> mydpvector;
//as data comes in
mydpvector.push_back(newdp);
vector<datapoint>::const_iterator cit=mydpvector.begin();
//now iterate everytime over the container
for(cit;cit!=mydpvector.end();cit++)
{
//get the data you need
}
//alternately if you need just the last element do this
mostrecentdp = mydpvector.back();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.