One of the "C + + primer daily Brushes" iterators

Source: Internet
Author: User


An Introduction to Iterators Overview

An iterator is a data type that examines the elements inside a container and traverses the elements.

An iterator (iterator) is an object that can be used to traverse some or all of the elements in a standard template's container, and each iterator object represents a definite address in the containers. Iterators modify the interface of regular pointers, so-called iterators are a conceptual abstraction: things that behave like iterators can be called iterators. However, iterators have many different abilities, which can unify the abstract container and the general algorithm organically.

The standard library defines an iterator type for each of the standard containers, including vectors. Iterator types provide a more generalized approach than subscript operations: All standard library containers define the appropriate iterator types, and only a handful of containers support subscript operations. Because iterators are applicable to all containers, current - generation C + + programs tend to use iterators rather than subscript operations to access container elements, even for vector types that support subscript operations.


An iterator can be used to access an element, and an iterator can move from one element to another.

iterator type of container

Each container type defines its own iterator type, such as vector:

Vector<int>::iterator ITER;

This J statement defines a variable named ITER whose data type is vector<int> the iterator type of righteousness. Each standard library container type defines a member named iterator , where the iterator has the same meaning as the actual iterator type.

Terminology Analysis: iterators and iterator Types

One of the reasons we may be puzzled when we first encounter the terminology about iterators is that the same term iterator often represents two different things. In general, it refers to the concept of an iterator, while in particular it refers to the specific iterator type defined by the container, such as vector<int>.

It is important to understand that there are many types that are used as iterators, and these types are conceptually relevant.

If a type supports a set of deterministic actions that can be used to traverse elements within a container and access the values of those elements, we call this type an iterator. each container class defines its own iterator type, which is used to access the elements within the container.

In other words, each container defines a type named iterator, and this type supports various operations (conceptual) iterators.

begin and end operations

Each container defines a pair of functions named Begin and end, which are used to return iterators. If there are elements in the container, the iterator returned by begin points to the first element:

Vector<int>::iterator iter =ivec.begin ();

The above statement initializes ITER to the value returned by the name of the vector operation. Assuming that the vector is not empty, after initialization, ITER means that the element is ivec[0].

The iterator returned by the end operation points to the next "end element of the vector". "End iterator exceeded" (Off-the-end iterator). Indicates that it points to an element that does not exist.

If the vector is empty, begin returns an iterator that is the same as the iterator returned by end.

The iterator returned by the end operation does not point to any actual element in the vector, but instead it acts as a Sentinel (Sentinel), indicating that we have processed all the elements in the vector.

self-increment and dereference operations of Vector iterators

The iterator type defines actions to get the element that the iterator points to, and allows us to move the iterator from one element to another.

An iterator type can use the dereference operator (dereference operator) (*) to access the element that the iterator points to:

*iter = 0;

The dereference operator returns the element to which the iterator is currently pointing. Assuming that ITER points to the first element of the vector object Ivec, then *iter and ivec[0] are pointing to the same element. The effect of the above statement is to assign the value of this element to 0.

Iterators are the use of a self-increment operator to move an iterator forward to the next element in the container.

Logically, the self-increment of an iterator is similar to the self-increment operation of an int object. The Int object to

That the result of the operation is to "add 1" to the int, while the iterator object is the iteration in the container

"Move one position forward". So, if ITER points to the first element, then ++iter points to

A second element.

PS: The iterator returned by the end operation does not point to any element, so it cannot be dereferenced or self-increment.

additional actions for iterators

Another pair of actions that can be performed on iterators is comparison: compare two iterators with the = = or! = operator, and if the two iterator objects point to the same element, they are equal, otherwise they are not equal.

examples of programs that iterators apply

Assuming that you have declared a vector<int>-type Ivec variable, to reset all its element values to 0, you can use the subscript operation to complete:

Reset all the elements in Ivec to 0

for (Vector<int>::size_type IX = 0;ix! = ivec.size (); ++ix)

Ivec[ix] = 0;

The above program iterates through the elements of the Ivec with a For loop, and the For Loop defines an index IX, which will increment by 1 for each iteration of the loop. The For loop body assigns each element of the Ivec a value of 0. A more typical practice is to use iterators to write loops:

Equivalent loop using iterators to resetall the elements in Ivecto 0

For (Vector<int>::iterator iter =ivec.begin (); ITER! = Ivec.end (); ++iter)

*iter = 0; Set element to which iterrefers to 0

See, this is much easier to write.

The For loop first defines ITER and initializes it to the first element that points to Ivec. The condition of the For loop tests whether ITER is not equal to the iterator returned by the end operation. Each iteration of ITER increases by 1, and the effect of this for loop is to process each element in the vector sequentially, starting with the first element of Ivec. Finally, ITER will point to the last element in the Ivec, and after the last element is processed, ITER increases by 1, which is equal to the return value of the end operation, in which case the loop terminates.

The statement in the For loop body accesses the value of the current element with the dereference operator. As with the subscript operator, the return value of the dereference operator is an lvalue, so it can be assigned to change its value. The effect of these loops is to assign all the elements in the Ivec to a value of 0.

Through the detailed analysis of the code above, it can be seen that this program with the subscript operator version achieves the same effect: starting with the first element of the vector, each element in the vector is set to 0.

It is important to note that the above procedure is safe if the vector is empty. If Ivec is empty, the iterator returned by begin does not point to any element--it cannot point to any element because there is no element. In this case, the iterator returned from the begin operation is the same as the value of the iterator returned from the end operation, so the test condition in the For statement immediately fails.

const_iterator

The previous program uses Vector::iterator to change the value of the elements in the vector. Each container type also defines a type named Const_iterator, which can only be used to read elements within a container, but cannot change its value.

When we dereference an ordinary iterator type, we get the non-const (section 2.5) of an element. And if we dereference the const_iterator type, we can get a reference to the Const object (Section 2.4), which, like any constant, cannot be overridden. For example, if text is a vector<string> type, the programmer wants to traverse it and output each element so that it can write a program like this:

Use const_iterator because we won ' Tchange the elements

for (Vector<string>::const_iteratoriter = Text.begin (); ITER! = Text.end (); ++iter)

cout << *iter << Endl; Printeach element in text

In addition to reading the value of an element from an iterator rather than assigning it, the loop

Like. Since this is only necessary to read with an iterator, there is no need to write, this defines the ITER

is a const_iterator type. When the const_iterator type is dereferenced, it returns a

A const value. Do not allow assignment with const_iterator:

for (Vector<string>::const_iteratoriter = Text.begin (); ITER! = Text.end (); + iter)

*iter = ""; Err Error: *iter is const

When using the Const_iterator type, we can get an iterator whose own value can be changed, but cannot be used to change the value of the element it points to. You can self-increment an iterator and use the dereference operator to read a value, but you cannot assign a value to the element. (Const_iterator, constant iterator, underscore "_")

Do not confuse the Const_iterator object with the Const iterator object. When declaring a const iterator, you must initialize the iterator. Once initialized, it is not possible to change its value:

Vector<int> Nums (10); Nums Isnonconst

const vector<int>::iterator CIT =nums.begin ();

*cit = 1; Ok:cit can change itsunderlying element

++cit; Error:can ' t change the value ofcit

That

Const_iterator, the constant iterator, the underscore "_", the value of the pointed element cannot be changed

Const iterator, a constant iterator, which points to an element object that cannot be changed,

The Const_iterator object can be used with a const vector or a non-const vector because it does not

can overwrite element values. This type of const iterator is of little use: once it is initialized, only

It can be used to rewrite the element it points to, but it cannot point to any other element.

Const Vector<int> Nines (10, 9); Define 10 Immutable "9" cannotchange elements in Nines

Error:cit2 could change the element itrefers to and Nines are const

Const Vector<int>::iterator Cit2 =nines.begin ();//const iterator, when declaring a const iterator, you must initialize the iterator, the constant iterator, the element object that points to cannot be changed,

Ok:it can ' t change an element value, soit can is used with a const vector<int>

Vector<int>::const_iterator it =nines.begin ();

*it = 10; Error: *it is const

++it; Ok:it isn ' t const so we canchange its value

That is

An iterator that cannot write elements

Vector<int>::const_iterator

An iterator whose value cannot change

Const Vector<int>::iterator


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.