C++ 将文件读入 hash_map

标签 c++ stl

我正在尝试读取单词列表并将它们连同它们在按字母顺序排序的文件中的位置一起保存在 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/

相关文章:

各种类型指针的 C++ 容器

C++添加对列表的元素

c++ - 使用 STL/Boost 查找和修改 vector 中的匹配元素

c++ - 在 C++ 中使用 STL 实现图形和树的良好且稳定的方法是什么?

c++ - 如何安装ConvNet库?

C++ 套接字 - 服务器不接受多个客户端 (linux)

C++使用算法过滤类 vector

c++ - 用于发送电子邮件的命令行 C++ 程序

c++ - dijkstra_shortest_paths Boost Graph Lib 1.57.0 失败

c++ - 具有相同散列值的值是否在同一个 std::unordered_map 桶中?