C++ 如何从常量映射中获取元素?

C++ 如何从常量映射中获取元素?,c++,dictionary,c++11,stl,constants,C++,Dictionary,C++11,Stl,Constants,我有一些类似bellow的结构来获取静态常量映射: struct SupportedPorts{ static std::map<std::string, std::string> init() { std::map<std::string, std::string> port; port["COM1"] = "ttySO1"; port["

我有一些类似bellow的结构来获取静态常量映射:

struct SupportedPorts{
    static std::map<std::string, std::string> init()
        {
          std::map<std::string, std::string> port;
          port["COM1"] = "ttySO1";
          port["COM2"] = "ttySO2";
          port["USB"]  = "ttyUSB0";
          return port;
        }
    static const std::map<std::string, std::string> supported_ports;
};
struct-SupportedPorts{
静态std::map init()
{
std::map端口;
端口[“COM1”]=“ttySO1”;
端口[“COM2”]=“ttySO2”;
端口[“USB”]=“ttyUSB0”;
返回端口;
}
静态常量std::映射支持的\u端口;
};
但当我试图通过键获取一些值时,我遇到了问题。在Exmaple类的cpp文件中:

#include "Example.h"

const std::map<std::string, std::string> SupportedPorts::supported_ports = SupportedPorts::init();

Example::Example(){
   std::cout << SupportedPorts::supported_ports['COM1'];
}
#包括“Example.h”
常量std::map SupportedPorts::supported_ports=SupportedPorts::init();
示例::示例(){

std::cout类模板std::map的运算符[]声明方式如下

T& operator[](const key_type& x);
T& operator[](key_type&& x);
也就是说,运算符返回一个非常量引用,而该引用可能不会对常量对象执行。并且运算符可能仅对非常量对象调用,因为它是在没有限定符
const
的情况下声明的

而是使用类似声明的函数
at

T& at(const key_type& x);
const T& at(const key_type& x) const;
此外,在该语句中使用多字节字符文字,而不是字符串文字

 std::cout << SupportedPorts::supported_ports['COM1'];

我看到您刚刚了解到,
[]
编辑映射或以下内容:关键点是,
[]
可能会在映射中插入一个元素。
常量T和运算符[]常量
无法做到这一点
 std::cout << SupportedPorts::supported_ports['COM1'];
 std::cout << SupportedPorts::supported_ports.at( "COM1" );
#include <iostream>
#include <string>
#include <map>

int main() 
{
    const std::map<std::string, std::string> supported_ports =
    {
        { "COM1",  "ttySO1" }, { "COM2", "ttySO2" }, { "USB", "ttyUSB0" }
    };
    
    std::cout << supported_ports.at( "COM1" ) << '\n';
    
    return 0;
}
ttySO1