Container vector and iterator + usage

Source: Internet
Author: User

Container vector declaration method: vector <type>: variable name (parameter)

Reference # incude <vector> before use

There are several initialization methods:

1 declaration initialization example: vector <int> VCT; default constructor is empty

Vector <int> vct1 (VCT) is initialized using declared containers.

The containers whose vector <int> vct2 (3, 5) is 3 are initialized and all three are equal to 5.

Vector <int> vct3 (5) is 3 and the initial value is 0.

2 vector is an ordered container and can be read through the subscript operator, but it must be an element that already exists in the container. Otherwise, an error will occur.

To facilitate traversal, each container has its own iterator.

Iterator concept: Used to traverse elements in a container and access the value of elements.

Declare the iterator vector of an integer container <int>: itrator itr;

Traverse elements in a container

For (itr = VCT. Begin (); I! = VCT. end (); itr ++)/* pay attention to VCT. end () is the next element of the last element in the container. It is a non-existent element. If the vector is empty, end is the same as the iterator returned by begin.

Cout <* itr; // here, * is the unreferenced operator. End cannot use * or the auto increment or decrement operator.

Another type of iterator is const_itrator. It can only access elements in the container, but cannot change elements.

Note: const vector <int >:: itrator is not equal to vector <int >:: const_itrator

The former can only access fixed elements and cannot perform operations such as * itr ++.

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.