​ 河北大学程序设计训练营

内容目录

[TOC]

set

set是集合,set不存在重复的元素,会按照从小到大进行排序

  • set集合中没有重复的元素
  • set中的元素都是排好序的

头文件引入

1
#include<set>

增加元素

1
insert()--在集合中插入元素

循环遍历

1
2
iterator begin()--指向第一个元素的位置
iterator end()--指向最后一个元素的下一个位置
1
2
3
for(set<int>::iterator it; it != s.end(); it++){
cout << *it << endl;
}

查询数目

1
size()--集合中元素的数目

删除数据

1
erase()--删除集合中的元素
1
void clear()--删除所有的数据

查找数据

1
find()--查找值对应的位置

注意

  • 如果元素存在那么返回其对应的位置

  • 否则返回end指针

    所以如果查找某个元素是否存在要做的条件判断

1
2
3
if(s.find(233)!=s.end()){
cout << "是的元素存在" << endl;
}

例题::set 集合的“交”与“并”

ios::sync_with_stdio(false);可以提高效率

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
51
52
53
#include<iostream>
#include<set>
using namespace std;

int main(){
ios::sync_with_stdio(false);
int m , n;
int x;
set<int> s , s2 , sj ,sb;
cin >> m >> n;

for( int i=0 ; i < m ; ++i){
cin >> x ;
s.insert(x);
}
for( int j=0 ; j < n ; ++j){
cin >> x ;
s2.insert(x);
}

//求交集
for(set<int>::iterator it = s.begin(); it != s.end(); ++ it){
if( s2.find(*it) != s2.end() ){
sj.insert(*it);
}
}

//求并集
for(set<int>::iterator it = s.begin(); it != s.end(); ++ it){
sb.insert(*it);
}
for(set<int>::iterator it = s2.begin(); it != s2.end(); ++ it){
sb.insert(*it);
}

//输出交集
cout << sj.size() ;
if(sj.size()!=0){
for(set<int>::iterator it = sj.begin(); it != sj.end(); ++ it){
cout << " " << *it;
}
}
cout << endl;

//输出并集
cout << sb.size() ;
if(sb.size()!=0){
for(set<int>::iterator it = sb.begin(); it != sb.end(); ++ it){
cout << " " << *it;
}
}

}

map

  • 第一个可以称为关键字(key),每个关键字只能在map中出现一次
  • key - value的对应

​ 以map<string , int> mp;举例

增加元素

1
2
3
4
5
mp["hx"] = 20;
mp["h3zh1"] = 21;
cout << mp["hx"] << endl;
cout << mp["h3zh1"] << endl;
cout << mp["wow"] << endl; //注意在键没有对应值时,会返回默认值,比如int就返回0,string返回空字符串

循环遍历

1
2
iterator begin()--指向第一个元素的位置
iterator end()--指向最后一个元素的下一个位置

查找函数

1
find()--查找值对应的位置

同set的find,如果找不到则返回最后一个元素的下一个位置

删除函数

1
erase()---根据键删除元素
1
clear()--清处所有的元素

例题::map 统计英文单词个数

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
#include<iostream>
#include<map>
using namespace std;

int main(){
int T;
int n;
cin >> T;
map<string , int> mp;

while(T--){

cin >> n;
string x;

while(n--){
cin >> x;
mp[x] += 1;
}

for(map<string , int>::iterator it=mp.begin();it!=mp.end();++it){
cout << it->first << " " << it->second << endl;
}
mp.clear();
}


}