Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting first 5 even numbers element from vector after reverse const iteration

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading