DEV Community

Mukit, Ataul
Mukit, Ataul

Posted on

2 1

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay