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

问题描述

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

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

但是当我尝试通过键获取一些值时遇到问题。在类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'];
}

我收到如下错误

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

解决方法

为类模板 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'];

 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