min(a,b)和max(a,b)
1 |
|
sort快排
1 |
|
binary_search二分查找
1 | int arr[] = {0,3,5,7,10,15,19,20,22,24,27}; |
vector(数组)
1 |
|
stack(栈)
1 |
|
queue(普通队列)
1 |
|
deque(双向队列)
1 |
|
list(双向链表)
1 |
|
set/multiset(集合)
multiset/set使用平衡二叉树的数据结构,插入和查找时间复杂度都是log n。
multiset和set的用法相同,只有一个区别:
- multiset中可以出现重复的元素。
- set中不会出现重复的元素,即使添加重复的元素,也会自动去重。
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
using namespace std;
int main()
{
int arr[10] = {5,1,2,4,6,4,3,5,8,8};//有重复的元素
int i;
multiset<int> ms; //创建一个空格multiset集合
for (i = 0; i < 10; i++) {
ms.insert(arr[i]);
}
multiset<int>::iterator p; //声明一个迭代器,类似于指针
for (p = ms.begin(); p != ms.end(); p++) {
//ms.begin() 返回一个迭代器,指向multiset的第一个元素
//ms.end() 返回一个迭代器,指向multiset最后一个元素的后面一个位置
cout << *p << " "; //1 2 3 4 4 5 5 6 8 8
}
cout << endl;
int length = ms.size(); //集合中元素的数量
bool isEmpty = ms.empty(); // 集合是否为空
int cnt = ms.count(8); //计算一个数出现的次数
cout<< length << " " << isEmpty << " " << cnt << endl; // 10 0 2
//查找元素,如果找到的话,返回一个迭代器指向找到的元素。如果没有找到的话,就返回multiset中元素总个数size
p = ms.find(8);
if (*p != ms.size()) {
cout<< "found " << *p << endl; //8
ms.erase(*p); //删除集合中所有的8,不是只删除一个。
cout<< "after delete , the size is "<< ms.size() << endl;
} else {
cout<<"not found"<<endl;
}
return 0;
}
map/multimap(映射、字典)
map和multimap的都是使用hash算法。
区别在于,map中的key只能出现一次,而multimap可以出现很多次。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
using namespace std;
int main()
{
map<string, string> m;
m["one"] = "hello";
m["two"] = "world";
m.insert(pair<string, string>("three", "C++"));
bool isEmpty = m.empty();
int length = m.size();
string s = m["one"]; //找到的话,就返回对应的值
cout<< s <<endl; // hello
s = m["four"]; //未找到的话,就返回一个类型零值
cout<< s <<endl; //返回空字符串
map<string, string>::iterator p;
p = m.find("one");
cout<< p->second << endl; //输出one对应的值--> hello
m.erase(p); //删除某个key
for (p = m.begin(); p != m.end(); p++) {
cout<< p->second << " "; // C++ world
}
m.clear(); //清空map
return 0;
}