Six major STL components-iterator, six major stl components

Source: Internet
Author: User

Six major STL components-iterator, six major stl components

Iterator:In addition to the subscript method that is common in other languages to access container elements, the C ++ language provides a completely new method-iterator (iterator) to access container elements. The iterator is similar to a reference and points to an element in the container. In another way, containers are generic data structures, while iterators are generic pointers that can point to elements. A container is equivalent to a storage cabinet, where many different items are like storage elements, such as bread, beer, apple, and cash. To get each object, you must use a tool that matches each object. For example, you must take out the bread and use a plate, take out the beer and use a cup, take out the apple and use a basket, and take out the cash and use a wallet. The role of the iterator is equivalent to the abstraction of the tool for retrieving items. The iterator refers to the tool for retrieving objects from the storage room in real life. The C ++ iterator is a data type that checks elements in a container and traverses elements.

 

Iterator type

You can use five iterators for STL data structures and algorithms. The following describes the five types:

Input iterators provides read-only access to data.

Output iterators provides write-only access to data.

Forward iterators provides read and write operations and can push the iterator Forward.

Bidirectional iterators provides read and write operations and can perform forward and backward operations.

Random access iterators provides read/write operations and can be moved randomly in data.

Although different STL implementation details are different, we can think of the above iterator as a kind of inheritance relationship. In this sense, the following iterator inherits from the previous iterator. Because of this inheritance relationship, you can use a Forward iterator as an output or input iterator. Similarly, if an algorithm requires a bidireal Al iterator, you can only use this type and random access iterator.

Pointer iterator

A pointer is also an iterator. This program also shows a major feature of STL-it can be used not only for its own class type, but also for any C or C ++ type. The following program shows how to use the pointer as an iterator for the STL find () algorithm to search for common arrays.

 1 #include <iostream.h> 2 #include <algorithm> 3  4 using namespace std; 5 #define SIZE 100 6 int iarray[SIZE]; 7  8 int main() 9 {10   iarray[20] = 50;11   int* ip = find(iarray, iarray + SIZE, 50);12   if (ip == iarray + SIZE)13      cout << "50 not found in array" << endl;14   else15      cout << *ip << " found in array" << endl;16   return 0;17 }

The program defines a global array of SIZE. Because it is a global variable, the runtime group is automatically initialized to zero. The following statement sets the location at index 20 to 50 and uses the find () algorithm to search for a value of 50:

Iarray [20] = 50;

Int * ip = find (iarray, iarray + SIZE, 50 );

The find () function accepts three parameters. The first two define the search range. Since the C and C ++ arrays are equivalent to pointers, The iarray expression points to the first element of the array. The second parameter, iarray + SIZE, is equivalent to the value of past-the-end, that is, the position behind the last element in the array. The third parameter is the value to be determined, that is, 50. The find () function returns an iterator of the same type as the first two parameters. Here is a pointer ip pointing to an integer.

If (ip = iarray + SIZE )...

If the expression is true, no value is specified in the search range. Otherwise, it is a pointer to a valid object, which can be displayed in the following statement ::

Cout <* ip <"found in array" <endl;

It is incorrect to test whether the return value of the function is equal to NULL. Do not use it as follows:

Int * ip = find (iarray, iarray + SIZE, 50 );

If (ip! = NULL )...//??? Incorrect

When using the STL function, you can only test whether the ip address is equal to the value of past-the-end. Although the ip address in this example is a C ++ pointer, its usage must comply with the STL iterator rules.

Container iterator

Although the C ++ pointer is also an iterator, the container iterator is used more. Unlike declaring an iterator as a pointer variable, you can use the container class method to obtain the iterator object. Two typical container classes are begin () and end (). They represent the entire container range in most containers. Other containers also provide reverse iterators using the rbegin () and rend () Methods to specify the object range in reverse order.

The following program creates a vector container (STL object equivalent to an array) and searches for it using an iterator. This program is the same as the one in the previous chapter.

 1 #include <iostream.h> 2 #include <algorithm> 3 #include <vector> 4  5 using namespace std; 6 vector<int> intVector(100); 7  8 void main() 9 {10   intVector[20] = 50;11   vector<int>::iterator intIter =12   find(intVector.begin(), intVector.end(), 50);13   if (intIter != intVector.end())14      cout << "Vector contains value " << *intIter << endl;15   else16      cout << "Vector does not contain 50" << endl;17 }

Constant iterator

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

Vector <int>: iterator first;

This statement creates an iterator for the vector <int> class. The following statement sets the iterator to the first object of intVector and sets the value of the object to 123 ::

First = intVector. begin ();

* First = 123;

This assignment is allowed for most container classes, except for Read-Only variables. To prevent misassignment, you can declare that the iterator is:

Const vector <int >:: 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.

Implementation source code of the specific iterator,Https://www.sgi.com/tech/stl/download.htmlYou can take a look.

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.