STL 是指C++的标准模板库(Standard Template Library),其中有一些常用算法和容器。
集合与映射就是两个常用的容器。
二者都支持insert 、find、count 、remove 操作,并且可以按照从小到大的顺序循环遍历其中的元素。
集合:set
set 就是数学上的集合——每个元素最多只能出现一次
set 中的元素已从小到大排好序,用一个 for循环即可从小到大遍历所有的元素
头文件
#include <set> //自动排序
声明
set<string> dict; //string集合
简单操作
操作 | 作用 |
---|---|
dict.insert (s) | 添加元素s |
dict.count (s) | 是否存在s,存在返回1,不存在返回0 |
dict.find (s) | 查找,返回地址 |
dict.begin() | 首地址 |
dict.end() | 尾地址 |
代码
#include <bits/stdc++.h>
using namespace std;
set<string> dict;
int main()
{
string s;
while(cin>>s)
dict.insert(s);
if(dict.count("hello"))cout<<"存在键值hello"<<endl;
set<string>::iterator add;
add = dict.find("hello");
cout<<*add<<endl;
for(set<string>::iterator it=dict.begin();it!=dict.end();++it)
cout<<*it<<endl;
return 0;
}
其中 set::iterator 的 iterator 的意思是迭代器,是 STL中的重要概念,类似于指针
int sum(int* begin, int* end) //其中参数begin和end就是仿照STL中的迭代器命名的
{
int *p=begin;
int ans=0;
for(int *p=begin; p!=end;p++)
ans+= *p;
return ans;
}
C++中set用法详解:(转载)
https://blog.csdn.net/yas12345678/article/details/52601454/
set 可以自定义排序的准则:(转载)
https://blog.csdn.net/qq_36677557/article/details/80157924
C++ set添加、删除和访问(STL set添加、删除和访问)元素详解:(转载)
http://c.biancheng.net/view/538.html
映射:map
map 就是从键(key)到值(value)的映射。
因为重载了 [ ] 运算符,使其可以像数组一样使用,map也称为 “关联数组”
例如:
map<string,int> month_name //表示“月份名字到月份编号”的映射
month_name["July"]=7; //赋值方式
头文件
#include <map>
代码
教材例题:
https://blog.csdn.net/weixin_42324771/article/details/88082882
C++中的STL中map用法详解:(转载)
https://www.cnblogs.com/fnlingnzb-learner/p/5833051.html