0

I have the following loop in more then one place:

for(int step = 1; step < timesteps; step++) ...

Then I had to change timesteps to start at 0. And I have to change it in more then one place.

May I take advantage of range based for loops in this situation? So may be I can write just

for(auto &step : timesteps) ...

In that case what kind of timesteps should be used? std::vector timesteps?

Before I forget to mention, timesteps is just an int i.e. int timesteps = 10;. Unknown at compile time, the user will define it.

p.s.: stl is preferred over boost.

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • what is the declaration of `timesteps`? – Steephen Aug 06 '18 at 03:11
  • 3
    Use your favourite range library, e.g. Boost.Range: `for(auto step : boost::irange(1, timesteps))` [Live on Wandbox](https://wandbox.org/permlink/ntXRTROAWfja5rwt) – Henri Menke Aug 06 '18 at 03:14
  • If `timesteps` is just an integer value, you can't use a range based for. There is no range in a single integer -- it is what it is and nothing more. (poet and didn't know it...) Technically, there is no `begin` or `end` for a single-integer. – David C. Rankin Aug 06 '18 at 03:24
  • You mean there is no similar to irange of boost in stl so far? – KcFnMi Aug 06 '18 at 03:29
  • Related: https://codereview.stackexchange.com/questions/51523/simple-integer-range-for-c11-range-based-for-loops https://stackoverflow.com/questions/7185437/is-there-a-range-class-in-c11-for-use-with-range-based-for-loops https://stackoverflow.com/questions/4930096/c0x-way-to-replace-forint-i-range-loops-with-range-based-for-loop – Jerry Jeremiah Aug 06 '18 at 03:36
  • what about defining: const int timesteps_begin = 1; and using that inside the initializer part of the for loop? – OrenIshShalom Aug 06 '18 at 03:38
  • I was thinking about that. But range based for will be shorter. – KcFnMi Aug 06 '18 at 03:40

0 Answers0