河北大学程序设计训练营
内容目录
[TOC]
set
set是集合,set不存在重复的元素,会按照从小到大进行排序
- set集合中没有重复的元素
- set中的元素都是排好序的
头文件引入
增加元素
循环遍历
1 2
| iterator begin()--指向第一个元素的位置 iterator end()--指向最后一个元素的下一个位置
|
1 2 3
| for(set<int>::iterator it; it != s.end(); it++){ cout << *it << endl; }
|
查询数目
删除数据
查找数据
注意
如果元素存在那么返回其对应的位置
否则返回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;
|
循环遍历
1 2
| iterator begin()--指向第一个元素的位置 iterator end()--指向最后一个元素的下一个位置
|
查找函数
同set的find,如果找不到则返回最后一个元素的下一个位置
删除函数
例题::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(); } }
|