다음과 같이 STL 맵에 쌍을 삽입하는 함수가 있습니다. 삽입하기 전에 새로운 메모리를 할당해야합니까?C++ STL 맵에 삽입하기 전에 new를 사용하여 메모리를 할당해야합니까?
char* foo(char* lnumber)
{
char* sData = “A,B,C”;
Char delim[] = “,”;
typedef std::map<std::string, std::string> TStrStrMap;
typedef std::pair<std::string, std::string> TStrStrPair;
TStrStrMap tMap;
if(strstr(sData,delim) != 0)
{
tok = strtok(sData, delim);
while((tok != NULL))
{
int bytes = strlen(tok)+1;
char* ll = new char[bytes];
memset(ll,0,bytes);
strcpy(ll,tok);
ll[bytes] = '\0';
int bytes1 = strlen("yes")+1;
char* ll1 = new char[bytes1];
memset(ll1,0,bytes1);
strcpy(ll1,”yes”);
ll1[bytes1] = '\0';
tMap.insert(TStrStrPair(ll,ll1));
tok = strtok(NULL, delim);
}
}
std::string strValue = tMap[lnumber];
return(strdup(strValue.c_str()));
}
삽입하기 전에 메모리를 새로 작성할 필요가 없습니다. STL은 메모리를 할당하고 개체를 컨테이너에 복사합니다. – billz
이 코드의 대부분은 거의 이해가 안됩니다. 왜 포인터도'new'도없이 진짜 C++을 쓰지 않으시겠습니까? –
어쩌면 질문을 잘 표현하여 올바른 방법을 묻는 것이 좋습니다. – Jason