Search code examples
c++stdstdvector

Any way to iterate over a vector in reverse or forwards based on a condition?


I am trying to do the following:

const bool b_condition = false;
const auto begin = b_condition ? arr.cbegin() : arr.crbegin();
// Will likely be different than arr.size(). Simplified here for example
const int size = arr.size();

std::for_each_n(begin, size, [](const Data& d) {
    // ...
});

I have to print the last or first size elements of a vector. Whether it is the last or first depends on b_condition.

const auto begin = b_condition ? arr.cbegin() : arr.crbegin();

The above code of course does not work as const_reverse_iterator and const_iterator are different types and only one can be stored in a variable.

After some research there does not seem to be a common base class for iterators so I cannot use that. Additionally, I understand this is extremely easy to do with a normal (non-std) for loop but I am trying to see if I can accomplish this with the standard library so I would prefer a std based answer.

Is there any way to iterate over the last or first size elements based on a condition with <algorithms>?


Solution

  • You'd have to make a new templated function to do the iteration to deal with the types being different. You can shortcut this slightly by using a lambda:

    const bool b_condition = false;
    
    const int size = arr.size();
    auto iterate = [&](auto begin) {
      std::for_each_n(begin, size, [](const Data& d) {
        //print d
      });
    };
    if (b_condition)
    {
      iterate(arr.cbegin());
    }
    else 
    {
      iterate(arr.crbegin());
    }