简体   繁体   中英

How to use an iterator pointing to a vector of structs c++?

I need help with my code . I don't understand how to use the returned pointers to access elements in a struct stored in a 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;

Now in main function I am trying to find all structs named receptionEvents that match a certain chFreqIndex using the below line :

int chFreqIndexCheck == 4;
     auto vpit = find_if( buffRxEvents.begin(), buffRxEvents.end(), [&] 
(receptionEvents const & m) { return m.chFreqIndex == chFreqIndexCheck;} );

Now my problem is how to use the vpit iterator to iterate over all found entries in my vector and how to access the data variables of each. Can any one help please?

The std::find family of functions returns an iterator to a single element (or end if nothing is found).

If you want to get all elements that matches your condition, then you could use std::copy_if to copy to a new container (possibly with the help of std::back_inserter ).

You can of course have your own loop, calling std::find_if multiple times and pass the previous vpit plus one as the beginning of the range you search through.

Or use std::for_each or a range-based for loop with a check for the current element to see if it matches your condition.

std::find_if only finds the first occurence. But you could search the next element beginning at the successor of the currently found element, such as:

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!
    }
}

Simpler, though, is a simple range based for loop:

for(auto e : buff)
{
     if( /* ... */ )
     { /* ... */ }
}

Edit:

but how exactly can I use it

You can just use it as if it was a pointer: *vpit to access the data the iterator "points to", vpit->x to access a member of, if data is a complex type (as in your example).

Example:

receptionEvents someCopy = *vpit; // copies entire struct
int cfIndex = vpit->chFreqIndex;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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