먼저 첫 번째 요소에 덮어 쓰기를 발생, 나는 다음과 같은 코드를 가지고,
map<char*, char*> records;
// id, value are buffer variables to store the text that returns from `strcpy()`
char *id = (char*)malloc(sizeof(char*) * 20);
char *value = (char*)malloc(sizeof(char*) * 20);
sql->open(dbFile);
sql->query("SELECT * FROM categories");
while(sql->fetch() != SQLITE_DONE){
// copy the text that returns from `sql->getValue`, then convert that text from `const unsigned char*` to `const char*`
strcpy(id, reinterpret_cast<const char*>(sql->getValue(0)));
strcpy(value, reinterpret_cast<const char*>(sql->getValue(1)));
// insert the values that in `id`,`value` as new item
records.insert(pair<char*, char*>(id, value));
}
free(id);
free(value);
이전 코드의 아이디어는 사용하여이 방법 sql->getValue(0)
를 반환하는 텍스트를 복사입니다 strcopy()
을 입력 한 다음 해당 텍스트를 const unsigned char*
에서 const char*
으로 변환 한 다음이 텍스트를 id
, value
변수에 저장 한 다음 id
, value
을 새 항목으로 삽입하십시오. 이전 단계는 데이터베이스에서 가져 오는 각 데이터에서 발생합니다.
는 생각이 더 명확히 : 예를 들어
, 데이터베이스에서 가져온 세 개의 행 (
fruits
,
vegetables
,
sweets
가) 있습니다. 지도 용기 내에 세 가지 데이터를 삽입 할 때
물론, 항목 수는 컨테이너 즉 세 가지 항목 제 (
fruits
)
제 (
vegetables
)
제 (
sweets
) 일 것이다.
제 경우에는 항목 수를 확인할 때 하나의 항목 만 있고 항목은 sweets
입니다.
이제 나머지 항목은 어디에 있습니까?
'std :: map'에 사용하는 키는 ** id가 아닌 ** id이며,'id'의'char *'입니다. std :: string을 사용하여 메모리 누수가 있다고 생각하는 것이 좋습니다. – Galik
마지막 질문에서'char *'의지도가 나쁜 디자인이라고 들었습니다. 할 수는 있지만이 코드와 마찬가지로 메모리 관리가 엉망이됩니다. – Blastfurnace
@ 갈릭 : 고마워, 정확히, 나는 알고 있었지만 문자열 유형을 사용하지 않고 문제를 해결하는 방법을 알지 못했다. –