c++ map 的三个参数
时间: 2024-06-17 15:01:01 浏览: 18
在C++中,`std::map` 是一个关联容器,它存储了键值对,其中每个键都是唯一的。`map` 的三个主要参数定义了它的内部实现和使用方式:
1. 第一个参数(模板参数)- 键的类型:这是用来存储容器中键的数据类型。例如,`std::map<int, std::string>` 表示键是整数类型,值是字符串类型。
2. 第二个参数(模板参数)- 值的类型:这是存储容器中值的数据类型。同样,`std::map<int, std::string>` 中,值是字符串类型。
3. 第三个参数(可选,默认为`std::less<key_type>`)- 比较器类型:用于比较键的默认排序方式。如果你想要自定义比较规则,可以提供一个实现了`std::binary_function<key_type, key_type, bool>`接口的函数对象或类型。例如,`std::map<int, std::string, std::greater<int>>` 使用升序排序。
相关问题
c++unordered_map三变量用法
C++中的unordered_map是一种关联容器,它将键映射到值。它的三个模板参数分别是键类型、值类型和哈希函数类型。其中,键类型和值类型是必须的,而哈希函数类型是可选的。如果不指定哈希函数类型,则默认使用std::hash作为哈希函数。下面是一个示例代码,展示了unordered_map的三个模板参数的用法:
```c++
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> mymap = {{"apple", 1}, {"banana", 2}, {"orange", 3}};
std::cout << "mymap[\"apple\"] = " << mymap["apple"] << std::endl;
std::cout << "mymap[\"banana\"] = " << mymap["banana"] << std::endl;
std::cout << "mymap[\"orange\"] = " << mymap["orange"] << std::endl;
return 0;
}
```
输出结果为:
```
mymap["apple"] = 1
mymap["banana"] = 2
mymap["orange"] = 3
```
c++ map 排序
在C 98中,map是自动根据键值进行排序的,如果你想要避免自动排序,可以通过使用自定义的比较函数来实现。你可以创建一个自定义的比较函数对象,并将其作为第三个模板参数传递给map。这个自定义的比较函数需要重载operator(),根据你的需求来定义比较规则。比如按照字符串长度进行排序,可以创建一个CmpByKeyLength的比较函数对象,重载operator()来比较字符串的长度。然后将这个比较函数对象作为map的第三个模板参数。
下面是一个示例代码,展示了如何使用自定义的比较函数来避免map的自动排序:
```cpp
#include <map>
#include <string>
#include <iostream>
using namespace std;
struct CmpByKeyLength {
bool operator()(const string& k1, const string& k2) {
return k1.length() < k2.length();
}
};
int main() {
map<string, int, CmpByKeyLength> mapStudent;
mapStudent["LiMin"] = 90;
mapStudent["ZiLinMi"] = 72;
mapStudent["BoB"] = 79;
map<string, int>::iterator iter = mapStudent.begin();
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++) {
cout << iter->first << " " << iter->second << endl;
}
return 0;
}
```
在上面的示例代码中,我们创建了一个CmpByKeyLength的比较函数对象,并将其作为map的第三个模板参数。这样就可以按照字符串长度进行排序,而不是按照默认的字典序排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)