forseqn
forseqn

Reputation: 39

C++ how to rewrite a range based for loop to a normal one?

I have a range based for loop like this:

for (auto& individual : population){
    individual.metadata.distance = distance(individual.tour);
}

Now I have to rewrite this into a normal for-loop in order to use OpenMP to parallelize my program, I have the following:

int length = population.size();
#pragma omp parallel for
for (int i = 0; i < length; i++){
    auto individual =* (population.begin() + i);
    individual.metadata.distance = distance(individual.tour);
}

However, the output becomes incorrect, so I am wondering if this is the way to rewrite a range based for-loop. Does anyone have any ideas?

Thanks in advance!

Upvotes: 2

Views: 1430

Answers (3)

Hristo Iliev
Hristo Iliev

Reputation: 74435

If population provides a random-access iterator - and it probably does, given your use of *(population.begin() + i) - then you could rewrite your loop like this:

#pragma omp parallel
for (sometype::iterator individual = population.begin();
     individual < population.end();
     individual++)
{
    individual->metadata.distance = distance(individual->tour);
}

OpenMP supports parallel loops over random-access iterators since version 3.0.

Upvotes: 2

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33904

Depends on what you need, If you are looking for each of the population parts then this will be equivalent:

for (Individual::iterator individual = population.begin(); individual != population.end(); individual++) {

This should be exactly the same as the auto for loop. If you need the count (as in i) you could approach it this way:

int counter = 0;
for (auto& individual : population){
    ...
    counter++;

This approach has the advantage of still using iterators, which are a good safe way to loop through your collections. But you can still check the count for whatever reason.

As to why your particular code is not working, use auto& individual.

Upvotes: 0

Mooing Duck
Mooing Duck

Reputation: 66951

auto individual =* (population.begin() + i);

This makes a copy, which appears to not be what you want. I think you meant this:

auto& individual =* (population.begin() + i);

Upvotes: 6

Related Questions