C++常用语法 —— 数据结构
因为太久没用 C++了,导致很多细节的语法已经记不得了。借着这一次刷的少量题回顾一下 C++的语法,以后总会有时候能用上的。
String
1 |
|
Vector
1 |
初始化
| 语法 | 含义 |
|---|---|
vector<int> v1 |
默认为空的 vector |
vector<int> v1(v2) |
默认 v2 副本的 v1 |
vector<int> v1(n, i) |
默认内容为 n 个元素 i |
vector<int> v1(n) |
默认内容为 n 个默认元素,以 int 为例,应是构建了包含 n 个 0 的 vector |
Vector的基本操作
1 | vector<int> test; |
Vector 的迭代器访问1
2
3
4vector<int> test;
vector<int>::iterator it;
for(it=test.begin();it!=test.end();it++)
cout<<*it<<endl;
算法1
2
3
reverse(test.begin(), test.end()); //颠倒
sort(test.begin(), test.end()); //升序排序
*为了降序排序1
2
3
4
5
6bool Comp(const int &a,const int &b)
{
return a>b;
}
sort(test.begin(),test.end(),Comp);
需要定义一个特殊的比较函数,比较函数的输入为 vector 内含有的元素。对于结构体,可以使用类似的方法定义.
*当插入对象是数组时1
2
3
4
5
6
7
8
9
10
11
12
using namespace std;
int main()
{
int out[3][2] = { 1, 2,
3, 4,
5, 6 };
vector <int*> v1;
v1.push_back(out[0]);
cout << v1[0][0] << endl; //1
return 0;
}
Pair
在进入 Map 之前我们需要先搞定 Pair 类。
1 | pair<int, int> test; |
Map
类似 python 的字典(不过灵活度大幅度下降。)
1 |
初始化
1 | map<int, int> map_int; |
其馀的初始化方法和 Vector 雷同,故不赘述。
Map的基本操作
1 | map<int, int> test; |
查找/读值1
2
3
4l_it=test.find(1); //查找元素,返回一个迭代器;若迭代器指向map的末尾,则不存在该元素
if(l_it==test.end())
cout<<"we do not find 112"<<endl;
else cout<<l_it->second<<endl; //由于返回的对象是一个迭代器,而迭代器指向的是一个Pair类型,故可以通过Pair类型的访问方法访问
遍历1
2
3
4
5map<int, int>::iterator it;
for (it = mp.begin(); it != mp.end(); it++){
printf("%d->%d\n", it->first, it->second);
}
return 0;
删除1
2mp.erase(k) ;//删除某一个键
mp.erase(it);//删除迭代器指向对象
unordered_map
效果和 map 非常相似,但是一般情况下,使用 unordered_map 更快。
1 |
Stack & Queue
Stack
1 |
|
Queue
1 |
|
Priority_queue
1 |
|
其馀操作如同普通的 queue。
自定义数据结构1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using namespace std;
//方法1
struct tmp1 //运算符重载<
{
int x;
tmp1(int a) {x = a;}
bool operator<(const tmp1& a) const
{
return x < a.x; //大顶堆
}
};
//方法2
struct tmp2 //重写仿函数
{
bool operator() (tmp1 a, tmp1 b)
{
return a.x < b.x; //大顶堆
}
};
int main()
{
tmp1 a(1);
tmp1 b(2);
tmp1 c(3);
priority_queue<tmp1> d;
d.push(b);
d.push(c);
d.push(a);
while (!d.empty())
{
cout << d.top().x << '\n';
d.pop();
}
cout << endl;
priority_queue<tmp1, vector<tmp1>, tmp2> f;
f.push(c);
f.push(b);
f.push(a);
while (!f.empty())
{
cout << f.top().x << '\n';
f.pop();
}
}
这里主要使用第一种方法吧:在数据结构重载运算符。