STL map

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表示层的名字。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值