Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to use the C?vector


May 11, 2021 C++


Table of contents


Vector is a very useful container in c. It can hold all types of objects like containers, and simply put, vector is a dynamic array that can hold any type of data, increasing and compressing it.
The array in C++ is very pit, is there a data type similar to the list in Python? I t's like vector! V ector is a collection of objects of the same type, each with a corresponding integer index value. L ike string objects, the standard library is responsible for managing the memory associated with the storage element. W e call vector a container because it can contain other objects. All objects in a container must be of the same type.

First, what is vector?

Vector is a sequence container that encapsulates an array of dynamic sizes. L ike any other type of container, it can hold various types of objects. It can simply be argued that a vector is a dynamic array capable of storing any type.

Second, the characteristics of the container

1. Order sequence

The elements in the order container are sorted in strict linear order. You can access the corresponding element by its position in the sequence.

2. Dynamic array

Fast direct access to any element in the sequence is supported, even through pointer calculations. The operation of adding/removing elements relatively quickly at the end of the sequence is provided.

3. Ability to sense memory allocators (Allocator-aware)

The container uses a memory allocator object to dynamically handle its storage needs.

Third, the basic function implementation

1. Constructor

  • vector() Create an empty vector
  • vector(int nSize) Create a vector with a number of elements nSize
  • vector(int nSize,const t& t) Create a vector with nSize elements and a value of t
  • vector(const vector&) Copy constructors
  • vector(begin,end) Copy elements of another array within the interval into vector

2. Add a function

  • void push_back(const T& x) Add an element X to the vector tail
  • iterator insert(iterator it,const T& x) Add an element x before the iterator in the vector points to the element
  • iterator insert(iterator it,int n,const T& x) Add n identical elements x before the iterator in the vector points to the element
  • iterator insert(iterator it,const_iterator first,const_iterator last) The iterator in the vector points to the data between the elements before inserting another vector of the same type

3. Delete the function

  • iterator erase(iterator it) in the vector to point to the element
  • iterator erase(iterator first,iterator last) Delete the elements in the vector
  • void pop_back() Delete the last element in the vector
  • void clear() Empty all elements in the vector

4. Traverse the function

  • reference at(int pos) a reference to the pos position element
  • reference front() a reference to the first element
  • reference back() a reference to the tail element
  • iterator begin() Returns the vector header pointer, pointing to the first element
  • iterator end() Returns the vector tail pointer, pointing to the next position of the last element of the vector
  • reverse_iterator rbegin() reverse iterator, pointing to the last element
  • reverse_iterator rend() Reverse iterator, pointing to the position before the first element

5. Judgment function

  • bool empty() const Determines whether the vector is empty and, if it is empty, there are no elements in the vector

6. Size function

  • int size() const Returns the number of elements in the vector
  • int capacity() const the maximum element value that the current vector can hold
  • int max_size() const the maximum allowable number of vector elements

7. Other functions

  • void swap(vector&) two vectors of the same type
  • void assign(int n,const T& x) Sets the value of the first n elements in the vector to x
  • void assign(const_iterator first,const_iterator last) The elements in the vector are set to the current vector element

8. Look clearly

1.push_back Add a data at the end of the array 2.pop_back remove the last data of the array 3.at get the numbered position of the data 4.begin gets the pointer to the array head 5.end gets the last cell of the array and the pointer 6. F ront gets the reference to the array header 7.back gets the reference to the last cell of the array 8.max se size gets how much 9.capacity current vector allocation size 10.size currently uses the size of the data 11.resize changes the size of the current usage data, if it is larger than the current use, populates the default value of 12.reserve C hanging the size of the space allocated by the current vecotr 13.erase delete pointer points to the data item 14.clear emptying the current vector15.rbegin returns the start pointer after the vector reversal (in fact, the original end-1) 16.rend returns the end pointer of the vector inverse (in fact, the original begin-1) 17.empty to determine whether the vector is empty 18.swap Exchange data with another vector

Fourth, the basic usage

#include < vector> 
using namespace std;

Five, a brief introduction

  1. Vector-lt;type-and-identifier
  2. Vector-lt;type-and-identifier (maximum capacity)
  3. Vector-lt;type-and-identifier (maximum capacity, initial all values)
  4. Int i s 5 s 1, 2, 3, 4, 5 s vector snr . . . type sgt;vi (I, i s2); / / get the value after the i index value of 3
  5. Vector< vector< int> >v; T wo-dimensional vector / / The most out-of-here is to have spaces. Otherwise, it cannot pass under the older compiler


Six, vector use instances

Precautions for using vector:

1, if you want to represent a longer vector length (need to save a lot of numbers for the vector inside), easy to cause memory leakage, and efficiency will be very low;

2, Vector as an argument to the function or return value, you need to pay attention to its writing:

double Distance(vector<int>&a, vector<int>&b)

One of the "and" must not be less !!!

Definition and initialization of vector objects

Similarly, before use, the import header file #include can use the use declaration: using std::vector; V ector is a class template. U se templates to write a class definition or function definition for several different data types. S o we can define vectors that hold string objects, or vectors that hold int values, or vectors that hold custom class type objects, such as Sales_items objects.
Declaring some type of object generated from a class template requires additional information, depending on the template. In the case of vector, you must explain what type of object vector holds and specify the type by putting the type in angle brackets after the class template name:

vector<T> v1; The save type is a T-object. The default constructor v1 is empty.
vector<T> v2(v1); v2 is a copy of v1.
vector<T> v3(n, i); v3 contains n elements with an i value.
vector<T> v4(n); v4 contains n copies of the element with the initialization of the value.

Note: 1, to create a non-empty vector object, you must give the value of the initialized element; H owever, the two vector objects must hold the same element type; T he constructor uses the number of elements to determine which vector object holds the element
number, the element value specifies the initial value of each element

Vector object dynamic growth:

An important property of vector objects (and other standard library container objects) is the possible efficient addition of elements at runtime.

Note: Because vectors grow efficiently, it is best to add elements dynamically when their values are known.

Instance:

Vector-lt;int;test;//build a vector, int is the data type of the array element, and the test is the dynamic array name

Here's how to use it simply:

vector<int>test;//建立一个vector
test.push_back(1);
test.push_back(2);//把1和2压入vector,这样test[0]就是1,test[1]就是2

Instance:

vector<vector<Point2f> > points; //定义一个二维数组
points[0].size();  //指第一行的列数


1, basic operation

(1) #include<vector>

(2) Create a vector object, vector<int> vec

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

(4) Access elements using the subsestation, cout<<vec[0]<<endl Remember that the sign-off starts at 0.

(5) Access elements using iterators.

vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
    cout<<*it<<endl;

(6) Insert elements: vec.insert(vec.begin()+i,a) Insert a in front of the i1 element;

(7) Delete elements: vec.erase(vec.begin()+2) Delete the third element

vec.erase(vec.begin()+i,vec.end()+j) ​; The deletion interval , i, j-1 , starts at 0

(8) Vector size: vec.size()

(9) Empty: vec.clear()

Special Tip: Here are the differences between the begin() and end() functions, front() and back().


2, important notes

Vector's elements can be not only int, double, string, but also structures, but be aware that structures need to be defined globally or errors will occur.

#include<stdio.h>  
#include<algorithm>  
#include<vector>  
#include<iostream>  
using namespace std;  
typedef struct rect  
{  
    int id;  
    int length;  
    int width;  
  //对于向量元素是结构体的,可在结构体内部定义比较函数,下面按照id,length,width升序排序。  
  bool operator< (const rect &a)  const  
    {  
        if(id!=a.id)  
            return id<a.id;  
        else  
        {  
            if(length!=a.length)  
                return length<a.length;  
            else  
                return width<a.width;  
        }  
    }  
}Rect;  
int main()  
{  
    vector<Rect> vec;  
    Rect rect;  
    rect.id=1;  
    rect.length=2;  
    rect.width=3;  
    vec.push_back(rect);  
    vector<Rect>::iterator it=vec.begin();  
    cout<<(*it).id<<' '<<(*it).length<<' '<<(*it).width<<endl;      
return 0;  
}  


3, algorithm

(1) Flip elements using reverse: header file #include .

reverse(vec.begin(),vec.end()); Flip the elements, i.e. in reverse order!

(In vecto r, if two iterators are required in a function, the 1st is generally not included)

(2) Sorting with sort: #include file is required.

Sort (vec.begin(), vec.end()) ;( the default is in ascending order, i.e. from small to large.

You can compare in descending order by overrideing the sort comparison function, as follows:

Define sort comparison functions:

bool Comp(const int &a,const int &b)
{
    return a>b;
}

When called: sort (vec.begin(), vec.end(), Comp), which sorts in descending order.


The element in the output Vector

vector<float> vecClass;

int nSize = vecClass.size();

Print vecClass, Method One:

for(int i=0;i<nSize;i++)    
{    
   cout<<vecClass[i]<<"     ";    
}    
   cout<<endl;   

It is important to note that when output by method one, the following table of arrays must be guaranteed to be integers.

Print vecclass, method 2:

for(int i=0;i<nSize;i++)    
{    
   cout<<vecClass.at(i)<<"     ";    
}    
   cout<<endl;    

Print vecClass, Method 3: It is not convenient to output a specified value

for(vector<float>::iterator it = vecClass.begin();it!=vecClass.end();it++)    
{    
    cout<<*it<<"   ";    
}    
    cout<<endl;    


Use of two-dimensional arrays:

#include "stdafx.h"  
#include <cv.h>  
#include <vector>   
#include <iostream>   
using namespace std;  
int main()  
{  
    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;//1  
    cout << v1[0][1] << endl;//2  
    cout << v1[1][0] << endl;//3  
    cout << v1[1][1] << endl;//4  
    cout << v1[2][0] << endl;//5  
    cout << v1[2][1] << endl;//6  
    return 0;  
}