DEV Community

Mukit, Ataul
Mukit, Ataul

Posted on

Elegant way to reverse iterate a std::vector in modern C++

template
class backwards {
T& _obj;
public:
backwards(T &obj) : _obj(obj) {}
auto begin() {return _obj.rbegin();}
auto end() {return _obj.rend();}
};

for (auto &elem : backwards(vec)) {
// ...useful code
}

Source: https://stackoverflow.com/questions/3610933/iterating-c-vector-from-the-end-to-the-begin

Top comments (0)

OSZAR »