DEV Community

loading...

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

lucpattyn profile image Mukit, Ataul ・1 min read

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

Discussion (0)

Forem Open with the Forem app