2012-11-02 2 views
-1

다음과 같이 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())); 
} 
+0

삽입하기 전에 메모리를 새로 작성할 필요가 없습니다. STL은 메모리를 할당하고 개체를 컨테이너에 복사합니다. – billz

+2

이 코드의 대부분은 거의 이해가 안됩니다. 왜 포인터도'new'도없이 진짜 C++을 쓰지 않으시겠습니까? –

+0

어쩌면 질문을 잘 표현하여 올바른 방법을 묻는 것이 좋습니다. – Jason

답변

2

특정 질문에 대답하려면 - 아니요, 표시 한 선언에 따라 직접 메모리를 할당 할 필요가 없습니다. std::string은 문자열 값에 대한 메모리를 관리하고 std::pairstd::string 값의 메모리를 처리하고 std::mapstd::pair 값의 메모리를 처리합니다.

귀하의 현재 코드는 ''버퍼로 '새 []'로 할당하고 있습니다. 귀하의 std::string 값은 데이터의 사본을 만들고있다, 그래서 그들과 함께 완료 whenyou 당신이 그들을 delete[]하는 등 필요 std::stringchar* 입력을 받아들이는 생성자를 가지고 있기 때문에, 그렇게 말

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) 
    { 
     char *tok = strtok(sData, delim); 
     while (tok != NULL) 
     { 
      int bytes = strlen(tok)+1; 
      char* ll = new char[bytes]; 
      strcpy(ll, tok); 
      int bytes1 = strlen("yes")+1; 
      char* ll1 = new char[bytes1]; 
      strcpy(ll1, "yes"); 
      tMap.insert(TStrStrPair(ll,ll1)); 
      delete[] ll; // <-- here 
      delete[] ll1; // <-- here 
      tok = strtok(NULL, delim); 
     } 
    } 

    std::string strValue = tMap[lnumber]; 
    return strdup(strValue.c_str()); 
} 

를 루프의 코드가 될 수 있습니다 다음과 같이 크게 단순화되었습니다.

// you really should be using std::string instead 
// of char* for the function's input and output... 
// 
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; 

    char *tok = strtok(sData, delim); 
    while (tok != NULL) 
    { 
     tMap.insert(TStrStrPair(tok, "yes")); 
     tok = strtok(NULL, delim); 
    } 

    std::string strValue = tMap[lnumber]; 
    return strdup(strValue.c_str()); 
} 
+0

또는 더 많은 C++ : http://coliru.stacked-crooked.com/a/2528388ba47e0736 –

관련 문제