我正在實作一個迭代器,它采用另一個浮點值生成輸入迭代器,如果檢測到上升則回傳 true。因此,迭代器作為軟體-ADC(模數轉換器)有效地作業。
我已將實際代碼最小化為以下內容:
#include <iterator>
template<typename It>
struct ADCFilter
{
using iterator_tag = std::input_iterator_tag;
ADCFilter(const float threshold, It it)
: It_{it}, Threshold_{threshold}, LastAnalogVal_{0}
{}
bool operator*()
{
float analog_val = *It_;
// rising edge
if (analog_val >= Threshold_ && LastAnalogVal_< Threshold_)
{
LastAnalogVal_ = analog_val;
return true;
}
// no rising edge
LastAnalogVal_ = analog_val;
return false;
}
ADCFilter operator () { It_; return *this; }
// Problem is here
ADCFilter operator (int) {auto self = *this; operator (); return self; }
private:
It It_;
float Threshold_;
float LastAnalogVal_;
};
如您所見,我需要快取最后一個模擬值。如果有人以這種方式使用迭代器:
std::vector<float> v = {...};
auto f = ADCFilter(0.2f, v.begin());
while(true) {
std::cout << *f ; // <- post inc
}
快取值永遠不會存盤,因為它只存在于回傳的副本中。盡管使用預增量不會發生此問題,因為我們正在取消參考實際的迭代器而不是它的副本。
我可以通過不實作它來輕松禁止使用后增量運算子,但根據https://en.cppreference.com/w/cpp/named_req/InputIterator必須為輸入迭代器實作它。
所以,問題是如何正確實作一個有狀態的輸入迭代器,它就像一個過濾器/映射器到另一個輸入迭代器?
uj5u.com熱心網友回復:
這可以通過重新實作運算子來完成,以便其內部資料僅保存bool值,而不是bool僅在迭代器被取消參考時派生該值的浮點值。
換句話說,解參考迭代器應該是:
bool operator*() const // It should be const, by the way
{
return value;
}
// ...
private:
bool value;
建構式將 初始化value為false。當前在解參考運算子中的所有代碼基本上都移到了 中operator (),其最終結果是更新的value. 沒有必要保存被迭代的真實值的副本,operator 可以簡單地將被包裝迭代器參考的當前值與被包裝迭代器遞增后的新值進行比較,并更新value.
后增量 運算子保持不變。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/391770.html
上一篇:Qt的電話聯系人串列
