2012-10-19 40 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讓我seg故障

回答

3

你從來沒有分配你的書矢量有任何元素。當您嘗試以下行時:

book[1] = "hello"; 

您試圖在未分配內存時存儲內容。

嘗試:

book.push_back("hello"); 

代替。

你也可以這樣做:

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

你沒有在你的book矢量字分配空間。嘗試像這樣:

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

或者你可以使用push_back()一個接一個地插入它們。

另外,索引從0開始,因此如果您使用1..4,則需要5個元素向量而不是4個,並且使用的內存量超過需要的量。

+0

非常感謝。有用! –