一、set
1.set的简单介绍
- set是按照一定次序存储元素的容器
- set中的元素是不能被修改的,只能支持增、删、查(否则元素可能变为无序的)
- set中元素的value标识它,并且每个value必须是唯一的
2.功能
set的底层实际是一个搜索树
- 可以查找关键字在不在(find()接口)
- 排序+去重
int main()
{
set<int> s;
s.insert(3);
s.insert(5);
s.insert(2);
s.insert(3); //已经有3,插入不进去(去重)
s.insert(1);
s.insert(7);
set<int>::iterator it = s.begin();
for (it; it != s.end(); ++it)
{
cout << *it<<' ';
}
cout << endl; //输出结果是有序的
it = s.find(3); //查找关键字
if (it != s.end())
cout << "找到了" << endl;
else
cout << "没找到" << endl;
}
查找:
it=it.find(3) //时间复杂度为O(logN)
it=std::find(it.begin(),it.end(),3) //时间复杂度为O(N)
删除:
上面代码为基础
s.erase(8); //set中有就删除,没有就不删
it=s.find(8);
s.erase(8); //set中有就删,没有就不能调用,否则编译器报错
3.multiset和set的简单区别
- multiset只能够排序,但不会去重,可以插入重复值
- 如果multiset里有多个相同值,调用find接口,找到了还会继续找
int main()
{
multiset<int> ms;
ms.insert(3);
ms.insert(1);
ms.insert(6);
ms.insert(9);
ms.insert(3); //还可以继续插入,不会去重
ms.insert(7);
for (auto it : ms)
{
cout << it << ' ';
}
cout << endl;
multiset<int>::iterator is = ms.begin();
is =ms.find(3);
if (is != ms.end())
cout << "找到了" << endl;
}
二、map
1.简单介绍
- map是关联容器,它按照特定的次序存储由key和value组合成的元素
- 键值key通常用于排序和唯一标识元素,而值value存储与此键值key关联的内容
- 键值key和value的类型可能不同,并且在map的内部,key与value通过成员类型value_type绑定在一起,取别名为pair
- map支持下标访问符
- 功能:通过关键字查找映射关联信息value
2.使用
int main()
{
map<string, string> mp;
mp.insert(pair<string, string>("苹果","apple"));
mp.insert(pair<string, string>("香蕉", "banana"));
mp.insert(pair<string, string>("梨","pear"));
mp.insert(pair<string, string>("梨", "pear")); //插入不进去
mp.insert(make_pair("桃子", "peach"));
map<string, string>::iterator it = mp.begin();
while (it != mp.end())
{
cout << it->first << ":" <<it->second<<endl;
++it;
}
}
从结果也可以看到,结果是按字典序列排序的,并且不能够插入key值
make_pair:实际上是一个函数模板
template<class K,class V>
inline std::pair<K, V> make_pair(const K& k, const V& v)
{
return std::pair<K,V>(k,v);
}
Q:给定一个字符串数组,里面存储多种水果,计算每种水果出现的次数
int main()
{
string s[] = { "苹果", "梨", "桃子", "苹果", "西瓜", "桃子", "苹果" };
map<string, int> mp;
for (const auto& str : s)
{
auto it = mp.find(str);
if (it != mp.end())
it->second++;
else
mp.insert(make_pair(str, 1));
}
map<string, int>::iterator it = mp.begin();
while (it != mp.end())
{
cout << it->first << ":" << it->second << endl;
++it;
}
}
map中有operator[]接口,返回值类型是value的引用
3.multimap
允许key冗余,但是没有operator[]这个接口
扫描二维码关注公众号,回复:
5930746 查看本文章
int main()
{
multimap<string, string> mp;
mp.insert(pair<string, string>("苹果","apple"));
mp.insert(pair<string, string>("香蕉", "banana"));
mp.insert(pair<string, string>("梨","pear"));
mp.insert(pair<string, string>("梨", "pear")); //可以重复插入
mp.insert(make_pair("桃子", "peach"));
map<string, string>::iterator it = mp.begin();
while (it != mp.end())
{
cout << it->first << ":" <<it->second<<endl;
++it;
}
}