加载无序地图

时间:2013-02-27 02:08:42

标签: c++ hashmap fstream

我有一个包含很多单词的文件,我正在尝试阅读和存储。我正在尝试创建一个地图排序。

我在程序开头声明了一个结构,它应该用于存储每个条目的信息。

typedef struct dictionary{ std::string word; unsigned char * hash; char *hex; } a_dictionary;
unordered_map<char * , a_dictionary * > Mymap;

这是我为保存单词而执行的代码,但由于某种原因,myMap没有正确编写

if (myfile.is_open())
        {
            LARGE_INTEGER freq, before, after;
            QueryPerformanceFrequency(&freq);
            QueryPerformanceCounter(&before);
            while ( myfile.good() )
            {
                getline (myfile,line);

                a_dictionary * dic = new dictionary(); // after each line create
                dic->word = line;


                const char * c= line.c_str();
                sha1::calc(c,line.length(), hash);//encrypts the word

                dic->hash = hash;

                sha1::toHexString(hash,hex_str);//encrypts the word
                dic->hex = hex_str;

                Mymap.insert(std::make_pair(hex_str, dic));
            }
            QueryPerformanceCounter(&after);
            float fElapsed = static_cast<float>(after.QuadPart - before.QuadPart) / freq.QuadPart;
            cout<<"Finished in "<<fElapsed;

我没有得到任何编译错误,当我在while循环中输出结构的变量时,它们出来了......但我的unordered_map永远不会被填充。

1 个答案:

答案 0 :(得分:0)

正如我上面评论的那样,看起来在循环的每次迭代中都会重用相同的 hash hex_str 缓冲区,所以每个都使用相同的密钥time(指针地址用作键,而不是字符串内容)

不知道 sha1 :: calc sha1 :: hash 的签名,或者你如何声明 hash hex_str ,我假设你正确地使用它们(我猜它们是c-arrays而且函数接受缓冲区的指针而不是null终止输出),最小的改变我会做的事情如下:

<强>解释

// no typedef necessary for struct in C++
struct dictionary {
    std::string word;
    std::vector<unsigned char> hash;
    // string instead of vector so it's hashable
    std::string hex;
};
std::unordered_map<std::string, dictionary*> Mymap;

<强>实施

if (myfile.is_open())
{
    LARGE_INTEGER freq, before, after;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&before);
    while ( myfile.good() )
    {
        getline (myfile,line);

        dictionary * dic = new dictionary(); // after each line create
        dic->word = line;

        const char * c= line.c_str();

        dic->hash.resize(SIZE_OF_HASH_BUFFER);
        sha1::calc(c, line.length(), &(dic->hash[0]));//encrypts the word

        dic->hex.resize(SIZE_OF_HEX_STR_BUFFER);
        sha1::toHexString(&(dic->hash[0]), &(dic->hex[0]));//encrypts the word

        if(!(Mymap.insert(std::make_pair(dic->hex, dic)).second))
        {
            // handle collision somehow...
        }
    }
    QueryPerformanceCounter(&after);
    float fElapsed = static_cast<float>(after.QuadPart - before.QuadPart) / freq.QuadPart;
    cout<<"Finished in "<<fElapsed;

根据您使用 Mymap 的方式,您可能希望将字典对象包装在智能指针中,或者只是让它们按值传递...如果没有更多上下文,就无法说出来。现在,您完全需要确保在完成 Mymap 的内容后释放与每个字典关联的内存...如果这是您真正想要的而不是为您完成它你可以自动使用智能指针,但你必须小心清理。