有人可以告訴我如何利用std::map.operator[]來獲得 a 的價值const std::map嗎?
例如:
檔案.h
#ifndef _FILE_H
#define _FILE_H
#include <map>
#include <string>
const std::map<std::string,std::string> STRINGS= {
{"COMPANY","MyCo"}
,{"YEAR","2022"}
};
#endif
檔案.cpp
#include "cpp_playground.h"
#include <iostream>
int main (void){
std::cout<< "Code by "<< STRINGS["COMPANY"] << " " << STRINGS["YEAR"] << std::endl;
}
使用 Visual Studio 2015 時出現此錯誤,但無法解釋
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
uj5u.com熱心網友回復:
operator[]in被定義為使用std::map給定鍵回傳對物件的參考 - 或者創建它,如果它不存在,它會修改映射,這就是它不是 const 方法的原因。該運算子沒有 const 版本,這就是您收到顯示錯誤的原因。
將std::map'at(...)函式用于僅訪問。請注意,std::out_of_range如果給定的鍵不包含在映射中,它將引發例外;在 C 20 或更高版本中,您可以使用contains()來檢查給定鍵是否存在。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/460427.html
上一篇:具有不同回傳型別的模板實體
