mercredi 2 août 2017

How to loop through an std::vector in repeating cycles

I am using an std::vector with C++ to store some items & retrieve them later. Following is how I am iterating through my vector.

std::vector<some_object> some_vector;
some_vector.resize(10);

for (auto it = some_vector.begin(); it != some_vector.end(); ++it) {
  int current_it_index = std::distance(some_vector.begin(), it);
}

I need the index per iteration. So, fetching it per iteration as demonstrated above.

Above loop works well but I want to loop through the vector in infinite cycles. How can I do that?

Now, i understand that the question comes, How do you stop the running loop if you let it run in repeating cycles. I am thinking to use an std::atomic<bool> as a variable to signal & break out of the loop which should work pretty well?

PS: Do note that I have taken std::vector as an example container to explain the question. It would be great if the suggested solution could work on std::array or other containers as well.

Aucun commentaire:

Enregistrer un commentaire