vendredi 26 mars 2021

How to get element from const map? [duplicate]

I have some struct like bellow to get static 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;
};

But I have problem when I trying get some value by key. In cpp file of class Exmaple:

#include "Example.h"

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

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

I get error like bellow:

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

Aucun commentaire:

Enregistrer un commentaire