C + + Learning Note (ix): vector use

Source: Internet
Author: User

Standard library type,vector represents a collection of objects, where all objects are of the same type. About vectors can be understood by comparing the groups. In some ways it is like the array.

It should be noted that the vector is a class template. The template itself is not a class or function, since it is called a template, it can be understood in fact a reference standard.

When you use a template, you need to indicate what type the compiler should define the objects in the template.

This is defined in the following way:

Vector<int> num; Num is a container that holds an int type Object

Note:vectors can accommodate most types of objects as their elements, but because the reference is not an object, the vector cannot contain references.

Initialization

Vector<t> v1 v1 is an empty vectorwith an element type of T type

Vector<t> v2 (v1) assigns all elements in the V1 to v2

Vector<t> v2 = v1 equivalent to the previous sentence

Vector<t> v3 (n,val) v3 has n repeating elements, each with a value of Val

Vector<t> v4 (N) V4 has n elements, each element is the default value

Vector<t> v5{a, B,c,...} Initialization of lists

Vector<t> v5={a, B,c,...}

Note the difference between {} and ().

Use push_back to add elements like vectors :

Push_back is a member function of a vector that can add a value as the last element of a vector.

Cases:

Vector<.int> v2;

for (int i = 0; I!=100; i++)

V2.push_back (i);

Note: Because vectors can add elements efficiently and quickly at run time. Therefore , it is sometimes unnecessary to define the size of a vector . Even the definition will be superfluous.

Other vector operations:

V.empty () if v is empty, returns True

V.size () returns The number of elements in V

V[] returns a reference to the nth element in v

<,<=,>,>=,!=,== are compared in dictionary order

C + + Learning Note (ix): vector use

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.