C ++ introduction to iterator (Collection) in C ++ STL)

Source: Internet
Author: User
Document directory
  • Iterator type
  • Pointer iterator
  • Container iterator
  • Constant iterator
Iterator

The iterator provides an access method for objects in a container and defines the range of objects in the container. The iterator is like a pointer. In fact, the pointer of C ++ is also an iterator. However, the iterator is not just a pointer, so you cannot think that they must have an address value. For example, an array index can also be considered as an iterator.

The iterator has different creation methods. The program may create an iterator as a variable. An STL container class may create an iterator to use a specific type of data. As a pointer, you must be able to use the * operator class to obtain data. You can also use other mathematical operators such as ++. Typically, the ++ operator is used to increment the iterator to access the next object in the container. If the iterator reaches the end of the last element in the container, the iterator changes to the past-the-end value. It is invalid to use a past-the-end pointer to access the object, as if to use NULL or to initialize the pointer.

Prompt

STL does not guarantee that it can arrive at an iterator from another iterator. For example, if you specify two iterators in different structures when sorting objects in a set, the second iterator cannot arrive from the first iterator, at this time, the program is doomed to fail. This is a price for STL flexibility.STL does not guarantee improper detection.

Iterator type

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

·Input iteratorsProvides read-only access to data.

·Output iteratorsWrite-only access to data

·Forward iteratorsProvides read/write operations and can push the iterator forward.

·Bidirectional iteratorsProvides read/write operations, and can perform forward and backward operations.

·Random access iteratorsRead/write operations are provided, and data can be moved randomly.

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

As shown in the following applet, 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. Listing 1, iterdemo. cpp, shows how to use the pointer as an iterator for STL's find () algorithm to search for common arrays.

Table1. iterdemo. cpp

#include <iostream.h>
#include <algorithm>
 
using namespace std;
 
#define SIZE 100
int iarray[SIZE];
 
int main()
{
  iarray[20] = 50;
  int* ip = find(iarray, iarray + SIZE, 50);
  if (ip == iarray + SIZE)
     cout << "50 not found in array" << endl;
  else
     cout << *ip << " found in array" << endl;
  return 0;
}

When I/O Stream library and STL algorithm header files are referenced (note that there is no. h suffix), this program tells the compiler to use the std namespace. The row that uses the std namespace is optional, because deleting the row does not cause Name Conflict for such a small program.

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 equivalentPast-the-endValue, 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.

Prompt

Remember to use the STL template. Therefore, STL functions are automatically constructed based on the data types they use.

To determineWhether find () is successful. In this example, test the ip address and Past-the-endWhether the values are equal:

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 STL functions, you can only test whether ip addresses andPast-the-endWhether the value is equal. 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. The container iterator is used in the same way as iterdemo. cpp, but unlike declaring the 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.

Listing 2. vectdemo. cpp

#include <iostream.h>
#include <algorithm>
#include <vector>
 
using namespace std;
 
vector<int> intVector(100);
 
void main()
{
  intVector[20] = 50;
  vector<int>::iterator intIter =
     find(intVector.begin(), intVector.end(), 50);
  if (intIter != intVector.end())
     cout << "Vector contains value " << *intIter << endl;
  else
     cout << "Vector does not contain 50" << endl;
}
 

Note: Use the following method to display the searched data:

cout << "Vector contains value " << *intIter << endl;
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.C ++ introduction to iterator in C ++ STL

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.