Use a regular iterator to iterate backwards, or struggle with reverse_iterator?

后端 未结 2 1889
予麋鹿
予麋鹿 2021-01-02 08:59

I recently learned about the right way to work with reverse iterators in C++ (specifically when you need to erase one). (See this question and this one.)

This is ho

相关标签:
2条回答
  • 2021-01-02 09:41

    The reason for reverse iterators is that the standard algorithms do not know how to iterate over a collection backwards. For example:

    #include <string>
    #include <algorithm>
    std::wstring foo(L"This is a test, with two letter a's involved.");
    std::find(foo.begin(), foo.end(), L'a'); // Returns an iterator pointing
                                            // to the first a character.
    std::find(foo.rbegin(), foo.rend(), L'a').base()-1; //Returns an iterator
                                                     // pointing to the last A.
    std::find(foo.end(), foo.begin(), L'a'); //WRONG!! (Buffer overrun)
    

    Use whichever iterator results in clearer code.

    0 讨论(0)
  • 2021-01-02 10:02

    For what it's worth, Scott Meyers' Effective STL recommends that you just stick with a regular ol' iterator (Item 26).

    0 讨论(0)
提交回复
热议问题