set相关知识
1.基础概念
set 是 C++ STL 容器,头文件:#include <set>
核心特性:
1.自动去重
2.自动排序
3.查找、插入、删除效率高
2.定义set
cpp
set<定义类型> 变量名
3.set相关函数
(1).insert()函数
insert是set中的插入函数,用来插入元素
例如:
cpp
set<int> s;
s.insert(7);//往set函数s中插入7
-------------------------------
set<int> s;
int a;
cin>>a;
s.insert(a);//往set函数s中插入a
(2).erase () 函数
erase是set中的删除函数,用来删除元素
例如:
cpp
set<int> s;
s.erase(2);//删除值为2的元素
(3).count()函数
count(x)
统计 x 出现次数,set 只有 0 或 1:
cpp
if(s.count(5)) cout << "有5";
(4).遍历set
遍历set时需要用到迭代器
1.传统迭代器
cpp
set<int>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<*it<<' ';
}
- auto 简写(C++11 及以上)
cpp
for(auto it = s.begin(); it != s.end(); ++it){
cout << *it;
}
4.例题
题目来源
https://www.topscoding.com/p/1722元素插入有序数组
题目描述
给你一个整数n和一个数列,这个数列保证从小到大排列,现要求将这个整数n插入到数列中,使新的数列仍然从小到大排列。(插入的数和数列的数不会重复)
输入格式
第一行一个整数n :等待插入的数
第二行一个整数m :数列中数的个数(m<100000)
第三行m个整数(空格隔开)
输出格式
一行整数:新的数列(空格隔开)
样例
输入
cpp
2
4
1 3 4 5
输出
cpp
1 2 3 4 5
解析
这是一道set函数的模板题,按照题目要求来做就行
题解
cpp
#include<bits/stdc++.h>
using namespace std;
set<int> s;
int main(){
int m,n,a;
cin>>n>>m;
for(int i=1;i<=m;i++){
cin>>a;
s.insert(a);//插入a
}
s.insert(n);//插入n
set<int>::iterator it;//迭代器遍历set
for(it=s.begin();it!=s.end();it++){
cout<<*it<<' ';
}
return 0;
}
map相关知识点
1、基础定义与头文件
头文件:#include <map>
核心特性:
1.自动去重
2.自动排序
3.查找、插入、删除效率高
(特性和set差不多)
2.定义set
cpp
map<关键字类型,值类型> 变量名
3.set相关函数
(有一些函数和set的函数一样,就不写了,写一点和set不一样的)
cpp
map<int,int> mp;
mp.insert(make_pair(变量名,变量名));//map的插入和set有点不同
mp.size(); // 返回键值对数量
mp.empty(); // 判断是否为空,空返回true
mp.begin(); // 迭代器的第一位
mp.end(); // 末尾后一位迭代器
4.map的迭代器
cpp
map<string,int>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<it->first<<' '<<it->second;
}
5.例题
题目来源
https://www.topscoding.com/p/2817
map的插入和遍历
题目描述
请从输入数据中读取 𝑛个同学的姓名和年龄,使用 map 进行存储,接着按照姓名字典序从小到大的顺序输出所有同学的姓名和年龄。
输入格式
第 1 行一个整数 𝑛 ,代表有 𝑛个同学( 1≤𝑛≤1500)。第 2 行到第 𝑛+1 行,
每行一个学生的姓名 𝑛𝑎𝑚𝑒(不超过 30 个字符)和年龄 𝑎𝑔𝑒( 8≤𝑎𝑔𝑒≤20),姓名和年龄之间用空格分隔(输入数据保证没有重名的学生)。
输出格式
按照姓名的字典序从小到大输出 𝑛行,每行一个学生的姓名和年龄,姓名和年龄之间用空格分隔。
样例
输入
cpp
3
Alex 15
Simba 20
Owen 15
输出
cpp
Alex 15
Owen 15
Simba 20
解析
这是一道和set函数一样的map函数的模板题,按照题目要求来做就行
题解
cpp
#include<bits/stdc++.h>
using namespace std;
map<string,int> s;
int main(){
string name;
int age;
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>name>>age;
s.insert(make_pair(name,age));
}
map<string,int>::iterator it;
for(it=s.begin();it!=s.end();it++){
cout<<it->first<<' '<<it->second<<'\n';
}
return 0;
}
创作不易,点赞关注哦