簡體   English   中英

具有移動end()的正向迭代器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM