CS/자료구조 & 알고리즘

[C++] const map 객체에 [key] 접근시 에러

ShovelingLife 2023. 11. 22. 20:27

map 클래스의 객체 a가 있고 이 객체가 const 화 되고 b라는 변수로 reference 됐다고 해보자.

b에 대한 value 를 접근함에 있어  b["key"] 이런식으로 접근하면 에러가 난다.

내용은 error : passing '~' as 'this' argument discards qualifiers 이하 생략. 이유는 const 화 된 map 객체에 ["key"]로 접근하면 그 값을 수정할 여지가 발생하기 때문이다.

value를 접근하는 다른 방법이 있다. 바로 .at를 쓰면 된다 b.at("key") 이렇게 접근하면 에러 없이 const화 된 map 객체의 value에 접근 가능하게된다.

#include <iostream>
#include <string>
#include <map>
#include <vector>

using namespace std;

int main()
{
	map<string, vector<int>> dict1
    {
    	{"AAA", { 1, 2, 0, 0 }},
    	{"B", { 2 }},
    };
    
    const map<string, vector<int>> dict2
    {
    	{"abc", { 3, 3, 1, 0 }},
    	{"def", { 0 }},
    };
    
    // ok	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 가 생성되는 오류의 여지가 있음.
    
    vector<int> v2 = dict2["abc"]; // 이를 컴파일 에러로 처리함.		
	vector<int> v2 = dict2.at("abc"); // compile ok	
}

 

출처