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"]);
}

编译和构建是好的。但是在我运行它之后,我得到了分段错误。需要帮助 真的不知道我的代码有什么问题。真的谢谢你!

4

2 回答 2

3

你从来没有分配你的书向量有任何元素。当您尝试此行时:

book[1] = "hello";

当您没有分配内存时,您正在尝试存储一些东西。

尝试:

book.push_back("hello");

反而。

你也可以这样做:

vector<string> book(4);
book[1] = "hello";
...
于 2012-10-19T05:15:40.700 回答
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,而且你使用的内存比需要的多。

于 2012-10-19T05:18:05.597 回答