Iterator and const_iterator

Source: Internet
Author: User

All the standard library containers define the corresponding iterator type. The iterator applies to all containers. Modern C ++ProgramIt is more inclined to use 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 to C is a bit like

(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.

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 <int> Nums (10); // Nums is nonconst

Const vector <int >:: iterator CIT = nums. Begin ();

* CIT = 1; // OK: CIT can change its underlying element

++ Cit; // error: Can't change the value of CIT

For example, read a piece of text into a vector object. Each word is stored as an element in the vector. Converts each word in a vector object to a lowercase letter. Output the converted elements in a vector object. Every eight words are output in one row.

ClassYou must use

Const_iterator; otherwise, it cannot be compiled.

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.