"C + + primer brushing every day" an iterator

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 storage container, each of which represents a definite address in an object. An iterator changes the interface of a regular pointer. A so-called iterator is a conceptual abstraction: something that behaves like an iterator can be called an iterator.

However, iterators have many different abilities. It 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 corresponding iterator type. 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.


Using iterators to access an element, an iterator can also move from one element to another.

iterator type of container

Each of the container types defines its own iterator type. 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 of the standard library container types defines a member named iterator . The iterator here has the same meaning as the iterator's actual type.

Terminology Analysis: iterators and iterator Types

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

The main point to understand is that there are a lot of types that are used as iterators. 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 such a 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. If the vector is not empty, after initialization. ITER refers to this element as 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.

Assuming the vector is empty, begin returns an iterator with the same iterator as the end return.

The iterator returned by the end operation does not point to the actual element in the vector, but instead, it is merely the function of a Sentinel (Sentinel). Indicates that we have finished processing all elements of 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 it agrees that we 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. If 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

said, the operation result is the int value "plus 1". The iterator object is the iteration in the container

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

A second element.

PS: Because the end operation returns an iterator that does not point to whatever element. Therefore, it cannot be dereferenced or self-increment.

other actions for iterators

Another pair of operations that can be run on an iterator is the comparison: two iterators with the = = or! = operator, assuming that two iterator objects point to the same element, they are equal. Otherwise, it is not equal.

Example of a program demo for an iterator application

If 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 Ivec with a For loop, which defines an index IX. Each iteration of the loop has an IX increment of 1.

The For loop body assigns a value of 0 to each element of the Ivec. 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 from the beginning of the Ivec first element. Finally, ITER will point to the last element in the Ivec. After the last element has been processed. When ITER adds 1, it will be equal to the return value of the end operation. In such a case. The loop terminates.

The statement in the For loop body uses the dereference operator to access the value of the current element. As with the subscript operator, the return value of the dereference operator is an lvalue. It is therefore possible to assign a value to change its value.

The effect of the above loop is to assign all elements in the Ivec to a value of 0.

Through the above specific analysis of the code, it can be seen that this program with the subscript operator version number to achieve the same effect: from the first element of the vector start. Set each element in the vector to 0.

It is important to note that the above procedure is safe if the vector is empty.

Suppose Ivec is empty. The iterator returned by begin does not point to whatever element--because there is no element. So it can't point to whatever element. In such a 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 fails immediately.

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.

Instead, suppose we dereference the const_iterator type. You can get a reference to a Const object (section 2.4), which cannot be overridden, as with any constant. For example, assuming that text is a vector<string> type, the program ape wants to traverse it and output each element. The ability to knock code 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. Because it only needs to be read with an iterator. No need to write, here's the definition of ITER

is a const_iterator type. When the const_iterator type is dereferenced. The return is a

A const value. Do not agree to use Const_iterator: to assign a value

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

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

When using the Const_iterator type. We are able to get an iterator whose own value can be changed, but cannot be used to change the value of the element it points to.

The ability to self-increment an iterator and use the dereference operator to read a value, but not to 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. A constant iterator, an underscore "_", that points to the value of an element that 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. A type like a const iterator is almost useless: once it is initialized, it is only

It can be used to rewrite the element it points to, but not to point it at whatever 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


Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

"C + + primer brushing every day" an iterator

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.