STL map
在C++中,map是标准模版库STL的一部分,它提供了一种关联容器,用于存储键值对(key-value pairs)。map容器中的元素是按照键的顺序自动排序的,这使得它非常适合需要快速查找和有序数据的场景。
定义和特性
- 键值对:
map
存储的是键值对,其中每个键都是唯一的。 - 排序:
map
中的元素按照键的顺序自动排序,通常是升序。 - 唯一性:每个键在
map
中只能出现一次。 - 双向迭代器:
map
提供了双向迭代器,可以向前和向后遍历元素。
map包含在头文件<map>
中,使用#include<map>
包含头文件。
声名map使用
std::map<key_type, value_type> myMap
其中key_type是键的类型,value_type是值的类型。
插入元素与访问元素
myMap[key] = value; // 插入元素
value = myMap[key]; // 访问元素
遍历map,需要使用迭代器,也就是C++ STL中的iterator,通过移动指针访问元素。
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "orange";
myMap[4] = "200";
size_t size = myMap.size();
std::cout << "Size of map: " << size << std::endl;
// 迭代遍历整个map
for (std::map<int, std::string>::iterator it = myMap.begin(); it!= myMap.end(); ++it){
std::cout << it->first << " : " << it->second << std::endl;
}
// 查看键值是否存在:`if(myMap.find(key) != myMap.end())`
if (myMap.find(2) != myMap.end()) {
std::cout << "Found element with key 2" << std::endl;
} else {
std::cout << "Element with key 2 not found" << std::endl;
}
//
if(myMap.find(5) != myMap.end()){
std::cout << "Element with key 5 not found" << std::endl;
}
myMap.erase(2); // 删除键值
std::cout << "After erasing element with key 2" << std::endl;
for (std::map<int, std::string>::iterator it = myMap.begin(); it!= myMap.end(); ++it){
std::cout << it->first << " : " << it->second << std::endl;
}
myMap.clear(); // 清空map
std::cout << "After clearing map" << std::endl;
int icounter = 0;
for (std::map<int, std::string>::iterator it = myMap.begin(); it!= myMap.end(); ++it){
std::cout <<icounter<< it->first << " : " << it->second << std::endl;
icounter++;
}
return 0;
}
输出结果为
Size of map: 4
1 : apple
2 : banana
3 : orange
4 : 200
Found element with key 2
After erasing element with key 2
1 : apple
3 : orange
4 : 200
After clearing map
另外在看YOLOV5GPU部署代码的时候看到batchnormal层中定义了权重map,std::map<std::string, Weights>
,
float *gamma = (float*)weightMap[lname + ".weight"].values;
float *beta = (float*)weightMap[lname + ".bias"].values;
float *mean = (float*)weightMap[lname + ".running_mean"].values;
float *var = (float*)weightMap[lname + ".running_var"].values;
int len = weightMap[lname + ".running_var"].count;
lname
表示层的名字。