"C + +" reverse iterator (rbegin,rend) (reproduced)

Source: Internet
Author: User
Tags sorts

Transferred from: http://blog.csdn.net/kjing/article/details/6936325

Rbegin and rend, very useful!

C + + Primer (Chinese version Fourth edition) No. 273 page

9.3.2 Begin and End members

The Begin and end operations produce iterators that point to the next position of the first element and the last element within the container, as shown below. These two iterators are typically used to mark the iteration range that contains all the elements in the container.

C.begin () returns an iterator that points to the first element of container C

C.end () returns an iterator that points to the next position of the last element of container C

C.rbegin () returns an inverse iterator that points to the last element of container C

C.rend () returns an inverse iterator that points to the position in front of the first element of container C

Each of these operations has two different versions: one is a const member and the other is a non-const member. What types these operations return depends on whether the container is const. If the container is not const, these operations return the iterator or reverse_iterator type. If the container is const, its return type is prefixed with the const_ prefix, which is the const_iterator and const_reverse_iterator types.

No. 353 Page

11.3.3 Reverse Iterator

A reverse iterator is an iterator that traverses a container in reverse. In other words, the container is traversed from the last element to the first element. The inverse iterator will reverse the meaning of self-increment (and decrement): For a reverse iterator, the + + operation accesses the previous element, while the--operation accesses the next element.

Recall that all containers define the begin and end members, respectively, to return an iterator that points to the next position of the first and last elements of the container. The container also defines the Rbegin and Rend members, returning a reverse iterator that points to the end of the container and the previous position of the first element. As with ordinary iterators, reverse iterators also have constant (const) and very nonconst types. Figure 11.1 illustrates the relationship between these four iterators using a vector type object that assumes the name VEC.

Suppose there is a vector container object that stores 0-9 of these 10 numbers in ascending order:

      Vector<int> Vec;      for (Vector<int>::size_type i = 0; I! = ten; ++i)            vec.push_back (i);//elements is 0,1,2,... 9

The following for loop will output these elements in reverse order:

      Reverse iterator of vector from back to front      vector<int>::reverse_iterator r_iter;      for (R_iter = Vec.rbegin (),//binds r_iter to last element            R_iter! = Vec.rend ();//rend refers 1 before 1st element< C4/>++r_iter)//decrements iterator one element          cout << *r_iter << Endl;//Prints 9,8,7,... 0

While it seems confusing to reverse the meaning of both the increment and decrement operators, it allows the programmer to transparently process the container forward or backward. For example, to arrange vectors in descending order, simply pass a pair of reverse iterators to sort:

      Sorts vec in "normal" order      sort (Vec.begin (), Vec.end ());      Sorts in reverse:puts smallest element at the end      of the Vec sort (vec.rbegin (), Vec.rend ());

1. The inverse iterator requires the use of the self-subtraction operator
It is not surprising that a reverse iterator can be defined from an iterator that supports both-and + +. After all, the goal of the reverse iterator is to move the iterator backwards through the sequence. Iterators on standard containers support both self-increment operations and self-subtraction operations. However, a stream iterator cannot create a reverse iterator because it cannot traverse the stream backwards.

2. Relationship between reverse iterators and other iterators
Suppose you have a string object named line that stores a comma-delimited list of words. We want to output line
The first word in the. Using find can be a simple way to accomplish this task:

      Find first element in a comma-separated list      string::iterator comma = find (Line.begin (), Line.end (), ', ');      cout << String (Line.begin (), comma) << Endl;

If there is a comma in line, comma points to the comma; otherwise, the value of comma is line.end (). When you export the contents of a string object from Line.begin () to comma, the output character starts from the beginning until a comma is encountered. If there is no comma in the string object, output the entire string string.
If you want to output the last word in the list, you can use a reverse iterator:

      Find last element in a comma-separated list      string::reverse_iterator Rcomma = Find (Line.rbegin (), Line.rend (), ', ') ;

Because Rbegin () and rend () are passed at this point, the function call starts searching backwards from the last character of line. When find finishes, if there is a comma in the list, then Rcomma points to its last comma, which is the first comma found in the reverse lookup. If there is no comma, the value of Rcomma is Line.rend ().

The interesting thing happened when I tried to output the word I found. Try directly:

      Wrong:will generate the word in reverse order      cout << string (Line.rbegin (), Rcomma) << Endl;

Generates false output. For example, if the input is: First,middle,last will output tsal!

Figure 2 illustrates this problem: when using a reverse iterator, the string object is processed in reverse order from the backward forward. In order to get the correct output, the reverse iterator line.rbegin () and Rcomma must be converted to a normal iterator that was moved back from the front. There is no need to convert line.rbegin (), because we know that the result of the conversion must be line.end (). Simply call the member functions provided by all the reverse iterator types to base conversion Rcomma:

     Ok:get a forward iterator and read to end of the line      cout << string (Rcomma.base (), Line.end ()) << Endl;

Assuming the input given earlier, the statement will output last.

Figure 2. The difference between a reverse iterator and an ordinary iterator

Figure 2 shows an object that visually explains the relationship between a normal iterator and a reverse iterator. For example, like Line_rbegin () and Line.end (), Rcomma and Rcomma.base () also point to different elements. In order to ensure that the range of forward and reverse processing elements is the same, these differences are necessary. Technically, the relationship between the normal iterator and the reverse iterator is designed to accommodate the left-closing range (9th. 2.1) of this nature, so, [Line.rbegin (), Rcomma) and [Rcomma.base (), Line.end ()) mark the line       The same element in the. The fact that a reverse iterator is used to represent a range and is not represented is an important conclusion: when a reverse iterator is initialized or assigned using a normal iterator, the resulting iterator does not point to the element that the original iterator points to.

"C + +" reverse iterator (rbegin,rend) (reproduced)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.