3.4 introduction to the iterator

Source: Internet
Author: User

1. Each container type defines its own iterator type

Vector <int>: iterator ITER;

2. Begin () returns the iterator pointing to the first element.

End () returns the iterator pointing to the last and next element.

3. Use * ITER to unreference the iterator

4. The const_iterator type can be changed by itself. However, the value of the object to which it points cannot be changed.

5. // an iterator that cannot write Elements

Vector <int>: const_iterator ITER;

// An iterator whose value cannot change

Const vector <int> iterator ITER;

6.

Code:
  1. # Include <iostream>
  2. # Include <vector>
  3. Using NamespaceSTD;
  4. IntMain ()
  5. {
  6. IntReadin = 0;
  7. Vector <Int> Ivec;
  8. Cout <"Input numbers :"<Endl;
  9. While(CIN> readin)
  10. {
  11. Ivec. push_back (readin );
  12. }
  13. If(Ivec. Size () = 0)
  14. {
  15. Cout <"No number Iput! "<Endl;
  16. Return0;
  17. }
  18. Vector <Int>:: Iterator iter = ivec. Begin ();
  19. For(; ITER <ivec. End ()-1; iter = ITER + 2)
  20. {
  21. Cout <* ITER + * (ITER + 1) <"";
  22. }
  23. Cout <Endl;
  24. If(ITER! = Ivec. End ())
  25. {
  26. Cout <"A number was not calculated :"<* (Ivec. End ()-1 );
  27. }
  28. }

7. Arithmetic Operations of the iterator:

ITER + N; ITER-N;

Iter1-iter2; // calculate the distance between two iterators, which is the signed type of different_type

Any operation to change the length of a vector will invalidate the iterator.

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.