How vectors are used in C + +

Source: Internet
Author: User

Original address: http://blog.csdn.net/duan19920101/article/details/50617190/

In C + +, vector is a very useful container.

Function: It can store various types of objects like a container, in short, a vector is a dynamic array that can hold any type and can add and compress data.

Vector in the C + + Standard Template Library part of the content, it is a multi-functional, able to operate a variety of data structures and algorithms of the template class and function library.

Special attention:

There are a few things to note about using vectors:

1, if you want to represent the length of the vector is very long (need to maintain a large number of vectors inside), prone to memory leaks, and inefficient;

2,vector as a function of the parameter or return value, you need to pay attention to its wording :

Double Distance (Vector<int>&a, Vector<int>&b) One of the "&" absolutely no less!!!

Example:vector<int>test;

Establishes a Vector,int data type for an array element, and test is a dynamic array name

The simple way to use it is as follows:

Build a vector

vector<int>test;

Press 1 and 2 into the vector .

Test.push_back (1);

Test.push_back (2);//At this time the dynamic array test[0] is 1,test[1] is 2

Examples of what you see:

vector<vector<point2f> > points; Define a two-dimensional array

Points[0].size (); Refers to the number of columns in the first row

1. Basic operation

(1) header file #include<vector>.

(2) Create vector object,vector<int> VEC;

(3) Insert number at tail: vec.push_back (a);

(4) Use subscript to access the element,cout<<vec[0]<<endl; remember that the subscript is starting from 0.

(5) Use iterators to access elements.

Vector<int>::iterator it;

For (It=vec.begin (); It!=vec.end (); it++)

cout<<*it<<endl;

(6) Insert element: Vec.insert (Vec.begin () +i,a); Insert a in front of the first I+1 element;

(7) Delete element: Vec.erase (Vec.begin () +2); Delete 3rd element

Vec.erase (Vec.begin () +i,vec.end () +j); Delete interval [i,j-1]; interval starting from 0

(8) Vector size: vec.size ();

(9) Empty: Vec.clear ();

Special Note: There is a difference between the Begin () and the end () function, front () and Back ()

2. Important Notes

The elements of a vector can be not only int,double,string, but also structs, but note that the structure is defined as global, otherwise it will go wrong.

#include <stdio.h>#include<algorthm>#include<vector>#include<iostream>using namespaceStd;typedefstructrect{intID; intlenght; intwidth; //for vector elements that are structural, you can define a comparison function within the structure, sorted by ID, lenght, Width ascending    BOOL operator< (ConstRect &a)Const    {        if(id! =a.id)returnID <a.id; Else        {            if(Lenght! =a.lenght)returnLenght <A.lenght; Else                returnWidth <A.width; }}}rect;intMainvoid) {vector<Rect>VEC;    Rect rect; Rect.id=1; Rect.lenght=2; Rect.width=3;    Vec.push_back (rect); Vector<rect>::iterator it =Vec.begin (); cout<< (*it) .id<<' '<< (*it) .lenght<<' '<< (*it) .width<<Endl; return 0;}

3. Algorithm

(1) Flip the element with reverse: Requires a header file #include<algorithm>

Reverse (Vec.begin (), Vec.end ()); Flips the elements, that is, in reverse order!

(in Vector, if two iterators are required in a function, they are not usually included in the latter one)

(2) Sorting by using sort: Requires header file #include<algorithm>

Sort (Vec.begin (), Vec.end ());(by default in ascending order, that is, from small to large).

You can compare functions in descending order by overriding the sort comparison, as follows:

To define a sort comparison function:

BOOL Comp (const int &A,CONST int &b)
{
Return a>b;
}
Called When: Sort (Vec.begin (), Vec.end (), Comp), so that it is sorted in descending order.

3.1 elements in the output vector

Vector<float> Vecclass;

int nSize = Vecclass.size ();

vector<float>Vecclass;intNSize =vecclass.size ();//Method 1: for(inti =0; i< nSize; i++) {cout<<vecClass[i]<<" ";} cout<<Endl;//Method 2: for(inti =0; i < nSize; i++) {cout<<vecclass.at (i) <<" ";} cout<<Endl;//Method 3: for(vector<float>::iterator it = Vecclass.begin (); It! = vecclass.end;it++) {cout<<*it<<" ";} cout<<endl;

It is important to note that when you output from method one, the subscript of the array must be guaranteed to be an integer. method Three Span style= "COLOR: #0000ff" > It is inconvenient to output a specified value

Application in a two-dimensional array:

#include"stdafx.h"#include<cv.h>#include<vector>#include<iostream>using namespacestd;intMainvoid){    //using namespace std;    int  out[3][2] = {1,2,                    3,4,                    5,6}; Vector<int*>v1; V1.push_back ( out[0]); V1.push_back ( out[1]); V1.push_back ( out[2]); cout<<v1[0][0]<<Endl; cout<<v1[0][1]<<Endl; cout<<v1[1][0]<<Endl; cout<<v1[1][1]<<Endl; cout<<v1[2][0]<<Endl; cout<<v1[2][]<<Endl; return 0;}

How vectors are used in C + + (GO)

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.