C++stl iterator

Source: Internet
Author: User

iterators

Iterators provide access to objects in a container, and define the scope of the objects in the container. An iterator is like a pointer. In fact, C + + pointers are also an iterator. However, iterators are not just pointers, so you can't think they must have address values. An array index, for example, can also be thought of as an iterator.

Iterators have a variety of different ways to create them. The program may create an iterator as a variable. An STL container class might create an iterator to use a particular type of data. As a pointer, you must be able to obtain data using the * operator class. You can also use other math operators such as + +. Typically, the + + operator is used to increment an iterator to access the next object in the container. if the iterator reaches the back of the last element in the container, the iterator becomes the Past-the-end value. It is illegal to use a past-the-end-worthy pointer to access an object, as if using null or as an initialized pointer.

Tips

The STL does not guarantee that an iterator can be reached from another iterator. For example, when you sort an object in a collection, if you specify two iterators in a different structure, and the second iterator cannot arrive from the first iterator, the program is doomed to fail. This is a cost to STL flexibility. STL does not guarantee the detection of unreasonable errors.

Types of iterators

For STL data structures and algorithms, you can use five types of iterators. The following is a brief description of these five types:

· Input iterators provides read-only access to the data.

· Output iterators provides write-only access to data

· The Forward iterators provides read and write operations and can forward iterators.

· The bidirectional iterators provides read and write operations and can be operated forward and backward.

· The random access iterators provides read and write operations and can be moved randomly in the data.

Although the different STL implementation details differ, the above iterators can be imagined as a class inheritance relationship. In this sense, the following iterator inherits from the iterator above. Because of this inheritance, you can use a forward iterator as an output or input iterator. Similarly, if an algorithm requires a bidirectional iterator, then only that type and random access iterator can be used.

Pointer iterator

As shown in the following applet, a pointer is also an iterator. The program also shows a major feature of the STL-it is not only available for its own class type, but also for any C or C + + type. Listing 1, Iterdemo.cpp, shows how to use pointers as iterators for the STL's find () algorithm to search for normal arrays.

Table 1. Iterdemo.cpp

1 #defineSIZE 1002 intIarray[size];3 4 intMain ()5 {6iarray[ -] = -;7   int* ip = Find (iarray, IArray + SIZE, -);8   if(IP = = IArray +SIZE)9cout <<"found in array"<<Endl;Ten   Else Onecout << *ip <<"found in array"<<Endl; A   return 0; -}

The I/O stream library and STL algorithm header files are referenced (note that there is no. h suffix), and the program tells the compiler to use the STD namespace. This line with the Std namespace is optional, because the row can be deleted without causing a name conflict for such a small program.

A global array of size is defined in the program. Because it is a global variable, the run-time array is automatically initialized to zero. The following statement sets the place element at index 20 to 50 and uses the Find () algorithm to search for the value 50:

iarray[; int );

The find () function accepts three parameters. the first two define the scope of the search. Because the C and C + + arrays are equivalent to pointers, the expression IArray points to the first element of the array. The second parameter, IArray + size, is equivalent to the past-the-end value, which is the trailing position of the last element in the array (that is, the value of the iterator end does not exist). The third parameter is the value to be positioned, which is 50. The find () function returns an iterator of the same type as the first two arguments, and here is a pointer to an integer IP.

Tips

You must remember that STL uses templates. As a result, STL functions are automatically constructed according to the type of data they use.

To determine if find () is successful, the example tests whether the IP and past-the-end values are equal:

if (IP = = iarray + SIZE) ...

If the expression is true, it indicates that there are no values specified in the scope of the search. Otherwise, a pointer to a legitimate object can be displayed with the following statement:

cout << *ip << "found in array" << Endl;

it is incorrect to test whether the function return value and null are equal. do not use it as follows:

int* IP = Find (iarray, IArray + SIZE, 50);
if (IP!  = NULL) ... // ??? Incorrect

When using STL functions, you can only test if the IP and past-the-end values are equal. Although in this case IP is a C + + pointer, its usage must conform to the rules of the STL iterator.

Container iterators

Although the C + + pointer is also an iterator, it uses more of a container iterator. The container iterator usage is the same as iterdemo.cpp, but unlike the iterator declaration as a pointer variable, you can use the container class method to get the iterator object. The two typical container class methods are begin () and end (). They represent the entire range of containers in most containers. Other containers also use the Rbegin () and Rend () methods to provide reverse iterators to specify the range of objects in reverse order.

The following program creates a vector container (STL and array-equivalent objects) and uses iterators to search for them. The program is the same as the procedure in the previous chapter.

Listing 2. Vectdemo.cpp

1Vector Intvector ( -);2 3 voidMain ()4 {5intvector[ -] = -;6Vector::iterator intiter =find (Intvector.begin (), Intvector.end (), -);7   if(Intiter! =intvector.end ())8cout <<"Vector contains value"<< *intiter <<Endl;9   ElseTencout <<"Vector does not contain"<<Endl; One}

Note the following methods are used to display the data you have searched for:

cout << "Vector contains value" << *intiter << Endl;
Const iterator

As with pointers, you can assign values to an iterator. For example, first declare an iterator:

Vector::iterator first;

The statement creates an iterator to the vector class. The following statement sets the iterator to the first object of Intvector and sets the object value it points to 123:

First = Intvector.begin ();
*first = 123;

This assignment is allowed for most container classes, except for read-only variables. To prevent error assignment, you can declare that the iterator is:

Const Vector::iterator Result;
result = Find (Intvector.begin (), Intvector.end (), value);
if (Result! = Intvector.end ())
  *result = 123;  // ???

Warning

Another way to prevent data from being changed is to declare the container as a const type.

Reprinted from: Http://blog.chinaunix.net/uid-20773165-id-1847758.html.

C++stl 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.