1

Is there a technical reason why std::filesystem::path doesn't offer reverse iterators (i.e., rbegin and rend)?

If I have a std::filesystem::path for /a/b/c/b/d/b/e and I want to find the first component that matches b, I can use std::find(p.begin(), p.end(), fs::path("b")).

But if I want to find the last component that matches b, I can't just switch to reverse iterators. I can write my own loop, but it seems like this would be a common operation that would have been "almost free" to implement.

Is there something about the design of the interface that would make it difficult to provide reverse iterators?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175
  • 2
    From [this page of cppreference.com](https://en.cppreference.com/w/cpp/iterator/reverse_iterator#Notes): "*std::reverse_iterator does not work with iterators whose dereference returns a reference to a member of *this (so-called "stashing iterators"). An example of a stashing iterator is std::filesystem::path::iterator.*" – Ruks Jul 29 '21 at 04:45
  • @Ruks: That explains it. Thanks! (If you convert that comment to an answer, I'll award the apoints.) – Adrian McCarthy Jul 29 '21 at 20:53

1 Answers1

1

According to this page of cppreference.com:

"std::reverse_iterator does not work with iterators whose dereference returns a reference to a member of *this (so-called "stashing iterators"). An example of a stashing iterator is std::filesystem::path::iterator."

Also from a page of boost.org, which says:

Path iterators store their value objects internally and when dereferenced return references to those internal objects. They cannot be used with iterator adaptors such as std::reverse_iterator that assume references obtained by dereferencing an iterator point to objects that out-live the iterator itself.

To find a more detailed explanation on stashing iterators, visit this page.

Ruks
  • 3,886
  • 1
  • 10
  • 22