C ++ dynamic array (vector)

About dynamic array

Sometimes, when we do question I would think there should be an array in the end how much it is appropriate, sometimes not known. So we hope to have the ability to change the size of the array at run time. It also appeared in the so-called dynamic arrays, dynamic arrays that are not determine the size of the array when the array in a statement. Dynamic array size can be changed at any time, flexible and convenient, contribute to the effective management of memory.

But in most cases, we use a static array, especially when playing the game. But sometimes if we use static array space will be fried, so I had to use dynamic arrays. But not very good writing dynamic arrays, so the C ++ SLT gives a vector container to help us.

vector container

Where the header file: the Vector

Where Type is the type :( defined as int, char, structure, string, etc.)

vector <Type> v; //默认初始化 v为空
vector <Type> v(v1); //用v1定义v
vector <Type> v(n); //v有n个值为0的元素
vector <Type> v(n, x); //v有n个值为x的元素
vector <Type> v[MAXN + 10]; //第一维大小是(MAXN + 10),第二维是动态的二维数组

Common operations:

v[i]; //v的第i个元素
v.clear() //清空v
v.push_back(x); //在尾部添加元素
v.pop_back() //删除末尾元素
v.insert(a.begin() + i, x) //在v[i]前面插入一个元素x
v.insert(a.begin() + i, n, x) //在v[i]前面插入n个元素x
v.insert(a.end(), x) //在v尾部插入一个元素x
v.insert(a.end(), n, x) //在v尾部插入n个元素x
v.erase(a.begin() + i) //删除v[i]
v.erase(a.begin() + i, a.begin() + j) //删除v[i]到v[j - 1]
v.erase(a.begin() + i, a.end()) //删除v[i]到最后一个元素
v.resize(n) //将数组大小调整为n
int vsz = v.size(); //v中元素的个数
bool isEmpty = v.empty(); //判断v是否为空,如果为空则是true,否则是false

Note: vector at an insertion or deletion, the following values ​​need to forward all, the time complexity of the algorithm is O (n) level. If you move frequently inefficient.

Published 33 original articles · won praise 47 · views 10000 +

Guess you like

Origin blog.csdn.net/SkeletonKing233/article/details/103795943