Learn to use iterator for work

Source: Internet
Author: User

Iterator is called an iterator. The iterator works with containers, such as the string and vector libraries. The iterator has two tasks: positioning and value. In my understanding, it is a high-level pointer. Why use it? I think it's flexible, but it's not as error-prone as a pointer!

Let's take a look at my toy experience:

 
# Include <iostream> # include <vector> using namespace STD; int main () {vector <int> vec1; vec1.push _ back (1); vec1.push _ back (2 ); vec1.push _ back (5); For (vector <int>: iterator iter = vec1.begin (); iter! = Vec1.end (); ++ ITER) {cout <* ITER <Endl ;}}

Explanation: premise: as long as the vector library is used, it must be included. I first defined an integer vec1 object. Interestingly, the vector class template uses the default destructor for initialization when defining vec1. It should be empty.

Add three numbers, 1, 2, and 5 to the vec1 object. just remember the interesting command. The object name plus the dot is added with the word push and underline, and then the real parameters of the word back and function are replaced by parentheses and values.

So how can we output the values in vec1 one by one? Here we use a safer and more flexible iterator. It must be a for or while loop. First define the matching iterator ITER,

 
Vector <int>: iterator ITER

I didn't write two colons at the beginning.ProgramError.

If the data type is string, replace int with string.

Finally, use

* ITER

Programming is still fun, haha.

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.