【问题标题】:How to get element from const map? [duplicate]如何从 const 映射中获取元素? [复制]
【发布时间】:2021-06-23 03:50:45
【问题描述】:

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

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

【问题讨论】:

标签: c++ dictionary c++11 stl constants


【解决方案1】:

运算符 [] 为类模板 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

【讨论】:

  • 关键点是[] 可能会在地图中插入一个元素。 const T&amp; operator[] const 无法做到这一点
猜你喜欢
  • 2012-04-07
  • 2020-04-06
  • 2013-07-25
  • 1970-01-01
  • 2018-01-13
  • 2012-02-26
  • 1970-01-01
  • 2013-01-13
  • 2020-10-26
相关资源
最近更新 更多