Reverse iterator and reverse iterator

Source: Internet
Author: User

Reverse iterator and reverse iterator

C ++ primer (fourth edition of Chinese Version) page 273rd

9.3.2 begin and end members

The begin and end operations generate an iterator pointing to the next position of the first and last elements in the container, as shown below. These two iterators are usually used to mark the range of iterations that contain all elements in the container.

C. begin () returns an iterator pointing to the first element of container c.

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

C. rbegin () returns a reverse iterator pointing to the last element of container c.

C. rend () returns a reverse iterator pointing to the position before the first element of container c.

Each of the preceding operations has two different versions: one is a const member and the other is a non-const member. The type returned by these operations 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, the return type must be prefixed with const _, that is, the const_iterator and const_reverse_iterator types.

 

Page 1

11.3.3 reverse iterator

The reverse iterator is an iterator that traverses containers in reverse order. That is, traverse the container from the last element to the first element. The reverse iterator reversed the meaning of auto-increment (and auto-increment): for reverse Iteration
The ++ operation accesses the previous element, while the -- operation accesses the next element.

Recall that all containers define the begin and end members and return the iterator pointing to the next position of the first and last elements of the container respectively. The container also defines rbegin and rend members and returns the reverse iterator pointing to the last element of the container and the previous position of the first element, respectively. Like normal iterators, reverse iterators also have constants and nonconst types. Figure 11.1 illustrates the relationship between the four iterators using a vector object named vec.

Figure 1 Comparison Between begin/end and rbegin/rend iterator

Assume there is a vector container object that stores the 10 numbers 0-9 in ascending order:

[Html]View plain copy
  1. Vector <int> vec;
  2. For (vector <int >:: size_type I = 0; I! = 10; ++ I)
  3. Vec. push_back (I); // elements are 0, 1, 2,... 9


 

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

[Html]View plain copy
  1. // Reverse iterator of vector from back to front
  2. Vector <int>: reverse_iterator r_iter;
  3. For (r_iter = vec. rbegin (); // binds r_iter to last element
  4. R_iter! = Vec. rend (); // rend refers 1 before 1st element
  5. + R_iter) // decrements iterator one element
  6. Cout <* r_iter <endl; // prints 9, 8, 7,... 0


 

Although the meanings of the inverted auto-increment and auto-Subtract operators seem confusing, they allow programmers to transparently forward or backward post-process containers. For example, to sort the vectors in descending order, you only need to pass a pair of reverse iterators to sort:

[Html]View plain copy
  1. // Sorts vec in "normal" order
  2. Sort (vec. begin (), vec. end ());
  3. // Sorts in reverse: puts smallest element at the end of vec
  4. Sort (vec. rbegin (), vec. rend ());


 

1. The inverse iterator must use the auto-subtraction operator.
You don't need to be surprised to define a reverse iterator from an iterator that supports both -- and ++. After all, the purpose of the reverse iterator is to move the iterator to reverse traversal sequence. The iterator on the standard container supports both Auto-increment and auto-increment operations. However, the stream iterator is not. Because it cannot reverse traverse the stream, the stream iterator cannot create a reverse iterator.
2. Relationship between the reverse iterator and other iterators
Assume that there is a string object named line that stores a comma-separated word list. We want to output the first word in line. You can use find to easily implement this task:

[Html]View plain copy
  1. // Find first element in a comma-separated list
  2. String: iterator comma = find (line. begin (), line. end (),',');
  3. Cout <string (line. begin (), comma) <endl;


 

If there is a comma in line, comma points to this comma; otherwise, the value of comma is line. end (). When outputting the content from line. begin () to comma in the string object, output the characters from the beginning until a comma is encountered. If the string object does not contain a comma, the entire string is output.
To output the last word in the list, use the reverse iterator:

[Html]View plain copy
  1. // Find last element in a comma-separated list
  2. String: reverse_iterator rcomma = find (line. rbegin (), line. rend (),',');


 

Because rbegin () and rend () are passed at this time, this function call starts to search back from the last character of line. When find is complete, if the list contains commas, rcomma points to its last comma, that is, the first comma found in reverse search. If no comma exists, the rcomma value is line. rend ().
An interesting thing happened when trying to output the words found. Try directly:

[Html]View plain copy
  1. // Wrong: will generate the word in reverse order
  2. Cout <string (line. rbegin (), rcomma) <endl;


 

False output is generated. For example, if the input is:
FIRST, MIDDLE, LAST
TSAL will be output!

Figure 2 illustrates this problem: when a reverse iterator is used, the string object is processed backward and forward in reverse order. To get the correct output, you must convert the reverse iterator line. rbegin () and rcomma to the normal iterator that moves from the front to the back. In fact, there is no need to convert line. rbegin (), because we know that the conversion result must be line. end (). You only need to call the members provided by all reverse iterator types.
The function base can be converted to rcomma:
 

[Html]View plain copy
  1. // OK: get a forward iterator and read to end of line
  2. Cout <string (rcomma. base (), line. end () <endl;


 

If the preceding input is used, the statement outputs the LAST value as expected.

Figure 2. Difference between reverse iterator and normal iterator



The object shown in Figure 2 intuitively explains the relationship between a common iterator and a reverse iterator. For example, like line_rbegin () and line. end (), rcomma and rcomma. base () also point to different elements. These differences are necessary to ensure that the range of forward and reverse processing elements is the same. Technically, the relationship between a common iterator and a reverse iterator is designed to adapt to the left closed range.
(Section 9.2.1). Therefore, [line. rbegin (), rcomma) and [rcomma. base (), line. end () marks the same element in line.
The reverse iterator is used to indicate the range, and the range is asymmetrical. This fact can be inferred from an important conclusion: when a normal iterator is used to initialize or assign values to the reverse iterator, the obtained iterator does not point to the element pointed to by the original iterator.

 

======================================

Record it for your reference.

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

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.