Iterator, const_iterator and const iterator

Source: Internet
Author: User

Vector is only one type of container. All the standard library containers define the corresponding iterator type. The iterator applies to all containers. Modern C ++ programs prefer to use the iterator instead of subscript operations to access container elements.
1. iterator, const_iterator: traverses elements in the container and accesses the values of these elements. Iterator can change the element value, but const_iterator cannot. The pointer is a bit like the pointer of C.
(Containers can + ITER, while vector can also ITER-N, ITER + n, n is an integer, iter1-iter2: The result is difference_type, the distance between the two elements of the table .)

2. The const_iterator object can be used for const vector or non-const vector. its own value can be changed (it can point to other elements), but it cannot rewrite the element value it points.

Example:

Const vector <int> nines (); // The element value in nines cannot be changed.

Const vecotr <int>: iterator cit2 = nines. Begin (); // error: it will cause changes to the value of the element it points to, while nines is a constant

Vector <int>: const_iterator it = nines. Begin (); // correct: Because the element value is not changed

* It = 10; // error: * It is a const.

+ + It; // correct: it can be changed because it is not a const.

 

3. Const iterator is different from const_iterator: It must be initialized when a const iterator is declared. Once initialized, it cannot be changed. Once initialized, it can only be used

Instead of directing it to other elements. (Therefore, const iterator is useless)

Example: vector Nums (10); // Nums is nonconst
Const vector: iterator CIT = nums. Begin ();
* CIT = 1; // OK: CIT can change its underlying element
++ Cit; // error: Can't change the value of CIT

 

 

From http://www.cnblogs.com/newgreen/archive/2010/08/03/1791583.html

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.