gpt4 book ai didi

C++ 将文件读入 hash_map

转载 作者:行者123 更新时间:2023-11-27 23:34:47 25 4
gpt4 key购买 nike

我正在尝试读取单词列表并将它们连同它们在按字母顺序排序的文件中的位置一起保存在 C++ STL hash_map 中。这个想法是稍后我需要能够判断一个字符串是否是一个词以及它是在另一个词之前还是之后。

ifstream f_dict ("dictionary.txt");
__gnu_cxx::hash_map <const char*, int> dictionary;
string temp_str;
int counter = 0;
while (!f_dict.eof()) {
f_dict >> temp_str;
dictionary.insert(make_pair(temp_str.c_str(), counter++));
}

我遇到的问题是它没有保存实际的单词。下面的 for 循环 打印出选择的单词,但 iter->first 始终为空。我错过了什么?

__gnu_cxx::hash_map<const char*, int>::iterator iter;
int i = 0;
for (iter = dictionary.begin(); iter != dictionary.end() && i < 150; iter++) {
cout << "word: " << iter->first << " index: " << iter->second << "\n";
i++;
}

最佳答案

您正在尝试为每个单词存储相同的 const char *,因为您从未为从文件中提取的单词创建任何新内存。如果您打印出从 temp_str.c_str() 返回的指针,它对于您的第一个循环中的每个调用都是相同的。在你的第二个循环中,你为 map 中的每条记录打印出相同的 char * (注意只有 1 个 b/c map 不允许重复),它在第一个循环内或在第一个循环和之间被设置为空字符串你的 for 循环。

这是演示问题和解决方案的示例代码。

#include <fstream>
#include <iostream>
#include <map>

using namespace std;

int main (int argc, char **argv)
{
ifstream file("test.txt");
map<const char *, int> dictionary;
map<string, int> strDictionary;

string temp_str;
int counter = 0;
while (!file.eof())
{
file >> temp_str;
cout << "PARSED: " << temp_str << "\n";
cout << "INSERTING: " << (unsigned long) temp_str.c_str() << "\n";
dictionary.insert(make_pair(temp_str.c_str(), counter));
strDictionary.insert(make_pair(temp_str, counter));
counter++;
}

cout << "Dictionary Size: " << dictionary.size() << "\n";
cout << "Str Dictionary Size: " << strDictionary.size() << "\n";

for (map<const char*, int>::const_iterator iter = dictionary.begin();
iter != dictionary.end();
++iter)
{
cout << "CHAR * DICTINARY: " << iter->first << " -> " << iter->second << "\n";
}

for (map<string, int>::const_iterator iter = strDictionary.begin();
iter != strDictionary.end();
++iter)
{
cout << "STR DICTIONARY: " << iter->first << " -> " << iter->second << "\n";
}
return 1;
}

关于C++ 将文件读入 hash_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1535249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com