Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a for loop in C++ and comparing the iterator to a negative number. Can an int store an unsigned int?

I want to:

  1. Store a default index value of "-1". If I finish iterating through a vector (using a for loop) and the index value is still "-1", I know none of the values checked by my for loop are matches.
  2. If a suitable value is found, update the index value to match the index of a value in the vector I'm iterating through.

Example:

int index = -1;
for (int i; i < vector.size(); i++){
    if (vector[i] == 1) {
        index = i;
        break;
    }
}

However, I always get a warning about "comparison between signed and unsigned integer expressions" from for (int i; i < vector.size(); i++). Unfortunately, I can't just use unsigned integer index = -1, since unsigned integers can't store negative values. Is it safe to store an unsigned int i value in int index, or do I need to find a different method of comparison? In this case, I would change the for loop to for (unsigned int i; i < vector.size(); i++), but leave the rest of the code the same.

I could use a separate boolean variable, but it just seems more cluttered to use the extra variable every time I run into this scenario. It would looks something like this:

bool found = false;
unsigned int index = -1;
for (unsigned int i; i < vector.size(); i++){
    if (vector[i] == 1) {
        index = i;
        bool = true;
        break;
    }
}
like image 909
Camoen Avatar asked Jan 24 '26 10:01

Camoen


1 Answers

Use iterator instead and as a bonus you do not have to write a loop at all:

auto it = std::find( vector.begin(), vector.end(), 1 );
if( it == vector.end() ) {
    ... // not found
}

you can use iterator with explicit loop though if you prefer.

auto it = vector.begin();
for( ; it != vector.end(); ++it ) {
     if( *it == 1 ) break;
}

if( it == vector.end() ) {
    ... // not found
}
auto index = std::distance( vector.begin(), it );
like image 111
Slava Avatar answered Jan 26 '26 23:01

Slava



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!