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

后端 未结 2 1904
予麋鹿
予麋鹿 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 
    #include 
    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.

提交回复
热议问题