Home > Software design >  Getting first 5 even numbers element from vector after reverse const iteration
Getting first 5 even numbers element from vector after reverse const iteration

Time:09-07

I have this code below that generates 15 random integers and uses them to initialize my vector, intVec. What I'm trying to do here is to iterate through the vector in reverse order and only print out the first 5 even numbers encountered while iterating.

I tried using the erase method to just print the first 5 elements but it keeps throwing me an exception error that says:

can't decrement vector iterator before begin

One of the requirements is that I have to use the const_reverse_iterator. Is there any simpler way to accomplish this?

 int main()
    {
    default_random_engine randObj;
    vector<int> intVec;

    for (int i = 0; i < 15; i  )
    {
        intVec.push_back(randObj());
    }
    
    vector<int>::const_reverse_iterator iter;
    for (iter = intVec.rbegin(); iter < intVec.rend();   iter) 
    {
        if (*iter % 2 == 0)
        {
            intVec.erase(intVec.begin() 5, intVec.end());
            cout << *iter << endl;
        }
    }
 };

CodePudding user response:

The requirement of having to use the const_reverse_iterator (note the "const") should be telling you that modifying the vector is not allowed. And nor is it even necessary: just use that iterator and run through the vector, printing out the elements that are even and, when doing so, incrementing a "counter" variable. When (or, technically, "if") that counter reaches 5, you can break out of the loop.

Note also that the const_reverse_iterator functions are crbegin() and crend().

Like this, for example:

#include<iostream>
#include <vector>
#include <random>

int main()
{
    std::default_random_engine randObj;
    std::vector<unsigned> intVec;

    for (int i = 0; i < 15; i  ) {
        intVec.push_back(randObj());
    }

    int count = 0;
    std::vector<unsigned>::const_reverse_iterator iter;
    for (iter = intVec.crbegin(); iter != intVec.crend();   iter) {
        if (*iter % 2 == 0)
        {
            std::cout << *iter << "\n";
            if (  count == 5) break;
        }
    }
    return 0;
}
  • Related