Can someone tell me how I can make use of std::map.operator[]
to get the value of a const std::map
?
For example:
file.h
#ifndef _FILE_H
#define _FILE_H
#include <map>
#include <string>
const std::map<std::string,std::string> STRINGS= {
{"COMPANY","MyCo"}
,{"YEAR","2022"}
};
#endif
file.cpp
#include "cpp_playground.h"
#include <iostream>
int main (void){
std::cout<< "Code by "<< STRINGS["COMPANY"] << " " << STRINGS["YEAR"] << std::endl;
}
With Visual Studio 2015 I get this error, but I can't interpret it
Severity Code Description Project File Line Suppression State
Error C2678 binary '[': no operator found which takes a left-hand operand of type 'const std::map<std::string,std::string,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion) cpp_playground d:\user\documents\visual studio 2015\projects\cpp_playground\cpp_playground.cpp 10
CodePudding user response:
The operator[]
in std::map
is defined to return a reference to the object with the given key - or create it, if it doesn't exist, which modifies the map, that's why it's not a const method. There is no const version of that operator, that's why you get the shown error.
Use std::map
's at(...)
function for access-only. Note that it throws a std::out_of_range
exception if the given key is not contained in the map; in C 20 or later you can use contains()
to check whether the given key exists.