본문 바로가기

프로그래밍/C-CPP

CPP/STL const map 객체에 [key] 접근시 에러

반응형





#include <iostream>

#include <map>

#include <vector>


int _tmain(int argc, _TCHAR* argv[])

{

std::map<std::string, std::vector<int>> dict1({ 

{ "AAA", { 1, 2, 0, 0 } },

{ "B", { 2 } }

});

const std::map<std::string, std::vector<int>> dict2({

{ "abc", { 3, 3, 1, 0 } },

{ "def", { 0 } }

});


// ok

std::vector<int> v1 = dict1["AAA"];


// compile error!

// ref : http://stackoverflow.com/questions/15614735/why-stdmapint-float-cant-use-operator-error-c2678

// dict2 가 const 로 정의되어 있음.

// [ 연산자는 자동으로 새로운 key, value 가 생성되는 오류의 여지가 있음.

// 이를 컴파일 에러로 처리함.

std::vector<int> v2 = dict2["abc"]; 


// compile ok

std::vector<int> v2 = dict2.at("abc");


return 0;

}



vs2013 의 에러 메시지는 다음과 같다. 원인을 찾기 위해 구글에서 검색할 때에는 에러코드인 C2678 binary operator map 등등으로 검색하였음.


error C2678: 이항 '[' : 왼쪽 피연산자로 'const std::map<std::string,std::vector<int,std::allocator<_Ty>>,std::less<_Kty>,std::allocator<std::pair<const _Kty,std::vector<_Ty,std::allocator<_Ty>>>>>' 형식을 사용하는 연산자가 없거나 허용되는 변환이 없습니다.

1>          with

1>          [

1>              _Ty=int

1>  ,            _Kty=std::string

1>          ]

1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\map(224): 'std::vector<int,std::allocator<_Ty>> &std::map<std::string,std::vector<_Ty,std::allocator<_Ty>>,std::less<_Kty>,std::allocator<std::pair<const _Kty,std::vector<_Ty,std::allocator<_Ty>>>>>::operator [](const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)'일 수 있습니다.

1>          with

1>          [

1>              _Ty=int

1>  ,            _Kty=std::string

1>          ]

1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\map(172): 또는       'std::vector<int,std::allocator<_Ty>> &std::map<std::string,std::vector<_Ty,std::allocator<_Ty>>,std::less<_Kty>,std::allocator<std::pair<const _Kty,std::vector<_Ty,std::allocator<_Ty>>>>>::operator [](std::basic_string<char,std::char_traits<char>,std::allocator<char>> &&)'

1>          with

1>          [

1>              _Ty=int

1>  ,            _Kty=std::string

1>          ]

1>          인수 목록 '(const std::map<std::string,std::vector<int,std::allocator<_Ty>>,std::less<_Kty>,std::allocator<std::pair<const _Kty,std::vector<_Ty,std::allocator<_Ty>>>>>, const char [4])'을(를) 일치시키는 동안

1>          with

1>          [

1>              _Ty=int

1>  ,            _Kty=std::string

1>          ]


728x90