One, vector container
1. What is a vector container
Vector is a sequence container (Sequence Container) that encapsulates a dynamic size array. Like any other type of container, it can store various types of objects. It can be simply considered that a vector is a dynamic array that can store any type.
2. Commonly used functions
1), constructor (initialization)
vector<int> a; //创建一个空vector
vector<int> a(10); //初始化了10个默认值为0的元素
vector<int> a(10, 1); //初始化了10个值为1的元素
//通过复制a初始化
vector<int> a(5, 1);
vector<int> b(a);
int a[5] = {
1, 2, 3, 4, 5};
//通过数组a的地址初始化,注意地址是从0到5(左闭右开区间)
vector<int> b(a, a+5);
2), add delete function
vector<int> a;
//在末尾加入元素1
a.push_back(1);
//在下标1指向的元素前插入一个5
a.insert(1, 5);
//在下标1指向元素前插入3个5
a.insert(1, 3, 6);
//将b的所有元素插入到a中
int b[5] = {
1, 2, 3, 4, 5};
a.insert(a.begin(), b, b+5);
//删除末尾元素
a.pop_back();
3. Remove duplicate elements from vector array
When writing the leetcode title "Sum of Three Numbers", it is necessary to de-duplicate the vector two-dimensional array. The set data structure is mainly used here.
#include<set>
#include<vector>
//这里声明一个二维vector数组
vector<vector<int>> res;
//...中间操作省略
set<vector<int>> s(res.begin(), res.end());
res.assign(s.begin(), s.end());
More specific reference documentation rookie tutorial
Two, string class
1. Character array in C language style
C-style strings originated from the C language and continue to be supported in C++. The string is actually a one-dimensional character array terminated with the null character'\0'. Therefore, a string ending in null contains the characters that make up the string.
There are a large number of functions in C++ to manipulate null-terminated strings, summarized as follows:
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char str1[11] = "Hello";
char str2[11] = "World";
char str3[11];
int len ;
// 复制 str1 到 str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
// 连接 str1 和 str2 结果在str1
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
// 连接后,str1 的总长度
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
//比较str1,str2是否相等,相同则返回0;如果<返回值小于0,如果s1>s2返回值大于0。
int res = strcmp(str1, str2);
cout << "strcmp(str1, str2): " << res <<endl;
//返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置
char ch = 'e';
int *a = strchr(s1, ch);
//返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置。
int *b = strstr(s1, s2);
return 0;
}
2. Commonly used special functions
1), string to int, long, float, double type
string s = "123.5";
//string 转 int;
cout << stoi(s) << endl;
//string 转 long
cout << stol(s) << endl;
//string 转 float
cout << stof(s) << endl;
//string 转 double
cout << stod(s) << endl;
For more details, please refer to the C language Chinese website