Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ comparing iterator with int

Is there a simple way to compare an iterator with an int?

I have a loop like this:

for (std::vector<mystruct>::const_iterator it = vec->begin(); it != vec->end(); ++it)

Instead of looping over the entire vector, I would like to just loop over the first 3 elements. However, the following does not compile:

for (std::vector<mystruct>::const_iterator it = vec->begin(); it < 3; ++it)

It there a good way to achieve the same effect?

like image 364
user788171 Avatar asked Dec 05 '25 10:12

user788171


2 Answers

since it's a vector, why not just access its position directly ?

if (vec->size() > 0)
{
    for (int i =0; i<3 && i< vec->size(); i++)
    {
        // vec[i] can be accessed directly
        //do stuff 
    } 
}
like image 51
Angel Koh Avatar answered Dec 06 '25 23:12

Angel Koh


std::next(vec->begin(), 3); will be the the iterator 3 places after the first, and so you can compare to it:

for (std::vector<mystruct>::const_iterator it = vec->begin(); it != std::next(vec->begin(), 3); ++it)

Your vector will need to have at least 3 elements inside it though.

like image 38
Pubby Avatar answered Dec 07 '25 01:12

Pubby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!