Talking about Vector
foreword
Most of the time when brushing questions in Leetcode these days, you need to use and operate vectors. The following is a summary of the common usage of vectors.
The definition of vector
Before using vector, you need to add #include<vector> at the head of the code
Define a vector separately:
vector<typename> name;
The typename here can be any basic type, such as int, double, char, structure, etc., or it can be an STL standard container such as vector, set, queue, etc., but pay attention to a detail. When defining typename as an STL container, you must enter >> Add a space in the middle, because C++11 will treat it as a displacement operation before, for example:
vector<vector<int>>name;//可能会被识别为位移操作符
vector<vector<int> > name;
Six initialization methods:
vector<int> a;//vector为空,size为0,没有分配内存空间
vector<int> b(a);//或者
vector<int>b = a;//拷贝初始化,b与a有相同的元素和容量
vector<int> c = {
1, 2, 3, 4, 5, 6};//拷贝列表中的元素
vector<int> d(c.begin() + 1, c.end() - 1);//d初始化为两个迭代器指定范围中元素的拷贝
vector<int> e(7);//e中将包含7个元素,每个元素进行缺省的值初始化,对于int,也就是被赋值为0,因此e被初始化为包含7个0
vector<int> f(6,3);//指定值初始化,f被初始化为包含7个值为3的int值
Two-dimensional array initialization
vector<vector<int> > a;//初始化一个二维的int型数组
Acquisition of elements in the vector container
Access by subscript
vector<int> a;
We can access the elements in a through subscripts, for example, a[1] == 2. Of course, the subscripts here are from 0 to a.size() - 1 like ordinary arrays.
access via iterator
An iterator is something like a pointer, defined as:
vector<int> :: iterator it;
The following is a small example of accessing a vector through an iterator:
it can be seen that a[i] and *(a.begin() + i) are equivalent.
vector common functions
push_back()
push_back(x) is to add an element x after the vector, and the time complexity is O(1)
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int>a;
for(int i = 1; i <= 5; i ++)a.push_back(i);//插入1~5
for(int i = 0; i < 5; i ++) cout<<a[i]<<" ";
return 0;
}
pop_back()
pop_back() is used to delete the tail element of the vector, and the time complexity is O(1)
size()
size() is used to get the number of elements in the vector, the time complexity is O(1), and the return type of size() is unsigned type
clear()
As the name implies, clear() is to clear all the elements in the vector, and the time complexity is O(n), where n is the number of elements in the vector
insert()
insert(it, x) is used to insert an element x to any iterator it of vector, and the time complexity is O(n)
erase()
erase() can delete a single element or all elements in a range
(1) Delete a single element
erase(it) delete the element whose iterator is it
(2) delete all elements in an interval
erase(a, b) means delete all elements in [a, b)
Let's do two questions below!
1470. Rearrange Arrays
1929. Array concatenation
For the solution, you can look at the solution on leetcode, or: my solution is here