如何从 const 映射中获取元素?

How to get element from const map?

我有一些像下面这样的结构来获取静态常量映射:

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;
};

但是当我尝试通过键获取一些值时遇到问题。在 class 的 cpp 文件中示例:

#include "Example.h"

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

Example::Example(){
   std::cout << SupportedPorts::supported_ports['COM1'];
}

我收到如下错误:

note: initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
       basic_string(const _CharT* __s, const _Alloc& __a = _Alloc());
error: conversion to non-const reference type ‘std::map<std::basic_string<char>, std::basic_string<char> >::key_type&& {aka class std::basic_string<char>&&}’ from rvalue of type ‘std::basic_string<char>’ [-fpermissive]
     std::cout << SupportedPorts::supported_ports['COM1'];
                                                         ^
(null):0: confused by earlier errors, bailing out

class 模板 std::map 的运算符 [] 声明如下

T& operator[](const key_type& x);
T& operator[](key_type&& x);

也就是运算符returns一个非常量引用,不能对常量对象做。并且运算符只能为非常量对象调用,因为它是在没有限定符 const.

的情况下声明的

而是使用声明为

的函数at
T& at(const key_type& x);
const T& at(const key_type& x) const;

此外,您在此语句中使用的是多字节字符文字而不是字符串文字

 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