[英]How to use an iterator pointing to a vector of structs c++?
我的code
需要幫助。 我不明白如何使用返回的pointers
訪問存儲在vector中的結構中的元素:
struct receptionEvents
{
int chFreqIndex; //0
int chSFIndex; //1
simtime_t endReceptionTime ;
double SNR; //2
bool collidedFlag; //0= false(Not Corrupted) 1=Corrupted
};
std::vector<receptionEvents> buffRxEvents;
現在,在主要功能我試圖找到一個名為所有的結構receptionEvents
匹配肯定chFreqIndex
使用下面的一行:
int chFreqIndexCheck == 4;
auto vpit = find_if( buffRxEvents.begin(), buffRxEvents.end(), [&]
(receptionEvents const & m) { return m.chFreqIndex == chFreqIndexCheck;} );
現在我的問題是如何使用vpit迭代器遍歷向量中所有找到的條目以及如何訪問每個變量的數據變量。 有人可以幫忙嗎?
std::find
函數系列將迭代器返回到單個元素(如果未找到,則end
)。
如果要獲取符合條件的所有元素,則可以使用std::copy_if
復制到新容器(可能在std::back_inserter
的幫助下)。
當然,您可以有自己的循環,多次調用std::find_if
並傳遞前一個vpit
加一個作為您搜索范圍的開始。
或者使用std::for_each
或基於范圍的for
循環 ,並檢查當前元素以查看其是否符合您的條件。
std::find_if
僅查找第一次出現。 但是您可以從當前找到的元素的后繼元素開始搜索下一個元素,例如:
auto vpit = buff.begin();
while(vpit != buff.end())
{
vpit = std::find_if(vpit, buff.end(), [](/*...*/){ /*...*/ });
if(vpit != buff.end())
{
// use it
++vpit; // for not finding current element AGAIN!
}
}
不過,更簡單的是基於循環的簡單范圍:
for(auto e : buff)
{
if( /* ... */ )
{ /* ... */ }
}
編輯:
但是我到底該怎么用
您可以像使用指針一樣使用它: *vpit
訪問迭代器“指向”的數據,如果數據是復雜類型,則vpit->x
可以訪問其成員(如您的示例)。
例:
receptionEvents someCopy = *vpit; // copies entire struct
int cfIndex = vpit->chFreqIndex;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.