2012-10-19 3 views
0
#include <unordered_map> 
#include <iostream> 
#include <string> 
#include <vector> 
#include <utility> 
#include <algorithm> 
using namespace std; 


unordered_map <string, int> setupDictionary(vector<string> book) 
{ 
    unordered_map<string, int> table; 
    for (int i =0;i< book.size(); i++) 
    { 
     string word = book[i]; 
     if(word != "") 
     { 
      if (table.find(word)==table.end()) 
      { 
       std::pair<std::string,int> myshopping (word,0); 
       table.insert(myshopping); 
      }else 
      { 
       int num = table[word]; 
       std::pair<std::string,int> myshopping (word,num+1); 
       table.insert(myshopping); 
      } 

     } 
    } 
    return table; 
} 

int main() 
{ 
    vector<string> book; 
    book[1] = "hello"; 
    book[2] = "world"; 
    book[3] = "hello"; 
    book[4] = "world2"; 
    unordered_map < string, int> dict= setupDictionary(book); 
    // printf("%s,%d",dict["hello"]); 
} 

컴파일 및 빌드가 좋습니다. 하지만 실행 한 후에 세그먼트 분할 오류가 발생했습니다. 도움이 필요하십니까 내 코드에서 뭐가 잘못 됐는지 모릅니다. 정말로 감사합니다!C++ unorderd_map 내게 오류가 발생했습니다.

답변

3

책 벡터에 요소를 할당하지 않았습니다. 이 줄을 시도 할 때 :

book[1] = "hello"; 

메모리를 할당하지 않은 상태에서 저장하려고합니다.

보십시오 : 대신

book.push_back("hello"); 

.

또한이 작업을 수행 할 수 있습니다 : 당신은 당신의 book 벡터의 단어를 공간을 할당하지 않았다

vector<string> book(4); 
book[1] = "hello"; 
... 
1

. 다음과 같이 시도하십시오 :

vector<string> book(4); 
book[0] = "hello"; 
book[1] = "world"; 
book[2] = "hello"; 
book[3] = "world2"; 

또는 push_back()을 사용하여 뒷면에 하나씩 삽입 할 수 있습니다.

또한 인덱스는 0부터 시작하므로 1..4를 사용하는 경우 4 개가 아닌 5 개의 요소 벡터가 필요하며 필요한 것보다 많은 메모리를 사용하고 있습니다.

+0

대단히 감사합니다. 유능한! –

관련 문제