본문 바로가기
C++

std::map에서 char array를 key로 사용하기

by leo21c 2021. 4. 8.
SMALL

아래와 같이 char array를 map의 키로 사용을 해보려고 테스트를 해봤다.

std::map<std::map<unsigned char*, int> test;

 

테스트 소스는 아래와 같다.

std::map<unsigned char*, int> test;
unsigned char first[9] = { '1','2','3','4','5','6','7','8', 0 };
unsigned char second[9] = { '0','2','3','4','5','6','7','0', 0 };
test[first] = 1;
test[second] = 2;

unsigned char temp[9];
memset(temp, 0, 9);
memcpy(temp, first, 8);

int k = test[temp];
int a = test[first];

입력을 해서 사용을 하는 경우에는 문제가 없다.

그러나 동적을 생성한 데이터를 키로 사용하려고 하면 문제가 발생한다.

 

위와 같이 temp를 char arrary로 동적 할당하고 first와 같은 배열 정보를 가지고 있지만 k와 a의 값은 같지 않다.

int k = test[temp]; 의 결과는 k = 0이다. 찾을 수 없다.

당연히 a = 1로 들어가 있다.

 

그렇다면 동적으로 생성된 char array를 키로 이용하기 위해서는 어떻게 해야 할까?

 

검색을 해서 찾은 정보이다.

std::array를 이용하는 방식이다.

std::map<std::array<unsigned char, 8>, int> test2;
std::array<unsigned char, 8> a1 = { '1','2','3','4','5','6','7','8' };
std::array<unsigned char, 8> b1 = { '0','2','3','4','5','6','7','0' };

std::array<unsigned char, 8> c1;
std::copy(a1.begin(), a1.end(), c1.begin());

test2[a1] = 1;
test2[b1] = 2;

k = test2[a1];
a = test2[b1];
a = test2[c1];
k = a;

위와 같이 c1을 std::array로 만들어서 c1에 a1의 데이터를 넣어 같에 만든 후 키로 사용해서 체크를 하면

k, a가 같은 값을 가지고 있는 것을 확인 할 수 있다.

LIST