文章目录
一、pair
1.头文件
std中
2.pair的应用
- pair是将2个数据组合成一个数据,当需要这样的需求时就可以使用pair,如map就是将key和value放在一起来保存。另一个应用是,当一个函数需要返回2个数据的时候,可以选择pair。
- pair的实现是一个结构体,主要的两个成员变量是
first
,second
。 - 因为是使用struct不是class,所以可以直接使用pair的成员变量。
3.定义(构造)
pair<int, double> p1(1, 2.4); //用给定值初始化
pair<int, double> p2(p1); //拷贝构造函数
pair<int, double> p3; //使用默认构造函数
p3 = make_pair(1, 1.2); //利用make_pair赋值
pair<int, double> p4; //使用默认构造函数
p3 = {1,2.1}; //使用{}
pair<int, double> p5; //给first和second赋值
p5.first = 1;
p5.second = 2.5;
3.访问
cout << p5.first << " " << p5.second << endl;
//1 2.5
// c++17 structured bindings of auto
auto [x, y] = p5;
cout << x << " " << y << endl;
//1 2.5
4.typedef简化
typedef pair<string, string> author;
author pro("May", "Lily");
author joye("James", "Joyce");
5.std::minmax()
template <class T>
pair <const T&,const T&> minmax (const T& a, const T& b);
功能:该函数返回一个pair,该pair的first元素的值为a,b中的最小值,second元素的值为a,b中的最大值
例如:
pair<float, float> size = minmax(width, height);
6.sort
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, int> node;
//重写排序方法
bool comp(const node &a, const node &b)
{
//常引用const T &xxx
return a.first < b.first || a.first == b.first && a.second <= b.second;
//<代表升序,>代表降序
}
int main()
{
node a[] = {{1, 2}, {2, 3}, {2, 1}};
int length = sizeof(a) / sizeof(node);
sort(a, a + length, comp);
for (int i = 0; i < length; i++)
{
cout << a[i].first << " " << a[i].second << endl;
}
return 0;
}
/**
1 2
2 1
2 3
*/
二、map
1.头文件
#include <map>
using namespace std;
2.创
map<int,char> m1; // 空
map<int,char> m2{{1,'a'},{2,'b'}}; // 初始化赋值
map<int,char> m3(m2); // 拷贝
map<k, v> m4(b, e); // 迭代器
3.插入
m[k] = v
m.insert({k,v})
如果要从0开始加的话,那么直接加就行,初始化值是0.
map<char,int> m;
cout << m[1]++ << endl; // 0
cout << m[1] << endl; // 1
4.查
有几个元素
m1.size()
单个元素
m1[k]
m1.at(k)
键值
- 迭代器:
map<int, char>::iterator it
- 键:
it->first
- 值:
it->second
foreach
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char, int> m;
m['c']=0;
m['a']=1;
for (auto e : m)
{
cout << e.first << " " << e.second << endl;
}
// only available with -std=c++17 or -std=gnu++17
for (auto [a,b] : m)
{
cout << a << " " << b << endl;
}
map<char, int>::iterator it;
for (it = m.begin(); it != m.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
// a 1
// c 10
return 0;
}
注意到输出的结果,自动按照key
键来排序了。
find
map<int, char>::iterator it = m1.find(1);
if (it!= m1.end()) // 找到了,没找到会返回和end()一样的迭代器值
{
cout << it->first << " " << it->second << endl;
}
三、unordered_map
#include <unordered_map>
unordered_map<char, int> m;
哈希表结构