mitchute
mitchute

Reputation: 431

Start value for vector loop

Say I have the following:

int numFields = 0;   
for ( auto & isFieldBlank : InputProcessor::numericFields_isBlank ) {
    if ( !isFieldBlank ) {
        numFields += 1;
    }
}

InputProcessor::numericFields_isBlank is a bool vector of all numeric input values indicating whether the input values are empty true or populated false.

I have two related questions:

  1. Is there a better way to count the populated fields in the vector?
  2. Is there a way to provide a starting index to the for loop iterator?

Upvotes: 0

Views: 114

Answers (2)

R Sahu
R Sahu

Reputation: 206567

Is there a better way to count the populated fields in the vector?

You can simplify the body of the for loop to:

    numFields += (!isFieldBlank);

The complete for loop will be

for ( auto & isFieldBlank : InputProcessor::numericFields_isBlank ) {
    numFields += (!isFieldBlank);
}

Is there a way to provide a starting index to the for loop iterator?

You certainly can. However, you will need to use a normal for loop, not a range-for loop.

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180500

A range based for loop will always run the entire range, you cant change that unless you adapt the range. What you can do though is use std::count/std::count_if to count the instances for you like

auto count = std::count(container.begin(), container.end(), true);

and to change the start and stop positions you can use std::next to move the iterator like

auto count = std::count(std::next(container.begin(), some_value),
                        std::next(container.end(), -some_other_value),
                        true);

Upvotes: 4

Related Questions