C + + Learning basics-Iterator Basics

Source: Internet
Author: User

Iterators are divided into two types: one is iterator and the other is const_iterator.
Both can access the elements in the container, and the difference is:
(1) The Const_iterator type can only be used to read elements within a container, cannot change its value, and iterator may change its value.
(2) When a const_iterator type is dereferenced, the return value is a const value and does not allow the assignment of its dereference.
Also do not confuse the Const_iterator object with the Const iterator object, the difference is:
(1) The const iterator must be initialized when it is declared, and its value cannot be changed once initialized, but it can change the value of the object it refers to.
(2) The Const_iterator object can change its value, but it is not allowed to change the value of the object it refers to (because when it is dereferenced, it returns a const value and is not allowed to be re-assigned).

The code snippet for the iterator type iterator is as follows:

Vector<string> vec1;for (Vector<string>::iterator iter = Vec1.begin (); ITER! = Vec1.end (); iter++) {cout< <*iter<<endl;*iter = "";//ok}

The code snippet for the Const_iterator type iterator is as follows:

for (Vector<string>::const_iterator iter = Vec1.begin (); ITER! = Vec1.end (); iter++) {cout<<*iter<< Endl;*iter = "";//error,because return value is const}

The code snippet that distinguishes const from Const_iterator is as follows:

Vector<string>::const_iterator iter1 = Vec1.begin (); *iter1 = "";//error, *iter1 is Constiter1++;//okconst vector& Lt;string>::iterator iter2 = Vec1.begin (); *iter2 = "";//okiter1++;//error,cannot Change const value

Subsequent updates ...

C + + Learning basics-Iterator Basics

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.