map和vector结合使用
时间: 2024-01-24 13:02:22 浏览: 50
在 C++ 中,map 和 vector 可以结合使用,以实现快速的查找和按顺序访问元素的功能。具体来说,可以使用 map 存储键值对,vector 存储 map 中的键值对,以实现根据键快速查找值,并能按顺序访问键值对的功能。
例如,可以定义一个 map<int, string>,用于存储 int 类型的键和 string 类型的值,然后将键值对按照键的顺序插入到一个 vector<pair<int, string>> 中,以实现按顺序访问键值对的功能。同时,可以使用 map 的 find() 方法快速查找特定键对应的值。
示例代码如下:
```cpp
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main() {
map<int, string> myMap;
myMap[1] = "one";
myMap[2] = "two";
myMap[3] = "three";
myMap[4] = "four";
myMap[5] = "five";
vector<pair<int, string>> myVec;
for (auto it = myMap.begin(); it != myMap.end(); it++) {
myVec.push_back(make_pair(it->first, it->second));
}
for (auto it = myVec.begin(); it != myVec.end(); it++) {
cout << "key: " << it->first << ", value: " << it->second << endl;
}
auto it = myMap.find(3);
if (it != myMap.end()) {
cout << "value of key 3 is " << it->second << endl;
}
return 0;
}
```
输出结果为:
```
key: 1, value: one
key: 2, value: two
key: 3, value: three
key: 4, value: four
key: 5, value: five
value of key 3 is three
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)