C++ c++;无序的地图给我带来了断层 #包括 #包括 #包括 #包括 #包括 #包括 使用名称空间std; 无序地图设置词典(矢量书) { 无序映射表; 对于(int i=0;i
编译和构建很好。 但在我运行它之后,我发现了一个错误。 需要帮助吗 我真的不知道我的代码出了什么问题。C++ c++;无序的地图给我带来了断层 #包括 #包括 #包括 #包括 #包括 #包括 使用名称空间std; 无序地图设置词典(矢量书) { 无序映射表; 对于(int i=0;i,c++,C++,编译和构建很好。 但在我运行它之后,我发现了一个错误。 需要帮助吗 我真的不知道我的代码出了什么问题。 谢谢你 您从未将书本向量分配给任何元素。当您尝试这一行时: #include <unordered_map> #include <iostream> #include <string> #include <vector> #include <utility> #include <algorithm> using names
谢谢你 您从未将书本向量分配给任何元素。当您尝试这一行时:
#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"]);
}
当您没有分配内存时,您正在尝试存储某些内容
尝试:
相反
您也可以这样做:
book.push_back("hello");
矢量书(4);
书[1]=“你好”;
...
您从未将书本向量分配给任何元素。当您尝试这一行时:
#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"]);
}
当您没有分配内存时,您正在尝试存储某些内容
尝试:
相反
您也可以这样做:
book.push_back("hello");
矢量书(4);
书[1]=“你好”;
...
您没有为书中的单词分配空间。试着这样做:
vector<string> book(4);
book[1] = "hello";
...
矢量书(4);
书籍[0]=“你好”;
书[1]=“世界”;
书[2]=“你好”;
书[3]=“世界2”;
或者您可以使用push_back()
将它们逐个插入后面
另外,索引从0开始,因此如果使用1..4,则需要5个元素的向量,而不是4个元素的向量,并且使用的内存比需要的要多。您没有为书中的单词分配空间。试着这样做:
vector<string> book(4);
book[1] = "hello";
...
矢量书(4);
书籍[0]=“你好”;
书[1]=“世界”;
书[2]=“你好”;
书[3]=“世界2”;
或者您可以使用push_back()
将它们逐个插入后面
另外,索引从0开始,所以如果使用1..4,则需要5个元素的向量,而不是4个元素的向量,并且使用的内存比需要的要多