I want to:
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;
}
}
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With