【问题标题】:It's add to hash_mapp strings with same keys它添加到具有相同键的 hash_mapp 字符串中
【发布时间】:2012-01-08 14:11:47
【问题描述】:

我认为在 hash_table 中我不能添加相同的值。我的意思是插入 (key1,value1) 然后再插入。

但在我的情况下,它添加了具有相同哈希值的相同字符串。 我试图将 BYTE* 作为键,但它仍然添加相同的字符串。

我使用过 HCRYPTHASH*,HCRYPTHASH,但它仍然无法正常工作。 也许需要重写 hash_map 的方法(在 C# 中,当 Dictionary 中的键是我自己的类时我遇到了麻烦,所以我只是重写了 GetHashCode 方法并重新定义了 Equals 方法)

#include <hash_map>
#include <string>
#include <iostream>
#include <Windows.h>
#include <WinCrypt.h>
#pragma comment(lib,"crypt32.lib")

int _tmain(int argc, _TCHAR* argv[])
{
    std::hash_map<BYTE*,std::string> table1;
    HCRYPTHASH hash1;
    HCRYPTPROV prov1;
    std::string a1="noname";
    std::pair<BYTE*,std::string> pair1;
    //insert first hash
    ::CryptAcquireContext(&prov1,NULL,NULL,PROV_RSA_AES,0);
    ::CryptCreateHash(prov1,CALG_MD4,0,0,&hash1);
    BYTE* arr=(BYTE*)a1.c_str();
    DWORD len0=strlen((char*)arr)+1;
    ::CryptHashData(hash1,arr,len0,0);
    BYTE get[16];
    DWORD len=16;
    ::CryptGetHashParam(hash1,HP_HASHVAL,get,&len,0);
    pair1.first=get;
    pair1.second=a1;
    table1.insert(pair1);
    /*----------------*/
    HCRYPTHASH hash2;
    HCRYPTPROV prov2;
    std::string a2="noname";
    std::pair<BYTE*,std::string> pair2;
    //insert second hash
    ::CryptAcquireContext(&prov2,NULL,NULL,PROV_RSA_AES,0);
    ::CryptCreateHash(prov2,CALG_MD4,0,0,&hash2);
    BYTE* arr1=(BYTE*)a2.c_str();
    DWORD len1=strlen((char*)arr1)+1;
    ::CryptHashData(hash2,arr1,len1,0);
    BYTE get1[16];
    DWORD len11=16;
    ::CryptGetHashParam(hash2,HP_HASHVAL,get1,&len11,0);
    pair2.first=get1;
    pair2.second=a2;
    table1.insert(pair2);
    for each(std::pair<BYTE*,std::string> x in table1)
    {
        std::cout<<x.first<<" - - "<<x.second<<"\n";
    }
    ::system("pause");
    return 0;
    }

【问题讨论】:

  • 检查insert返回值

标签: c++ stl hashmap


【解决方案1】:

您的大部分代码似乎与您的观察完全无关:std::hash_map&lt;BYTE*, std::string&gt;(实际上不是标准 C++ 类,尽管 std:: 的使用有些误导;散列图在 C++2011 中称为 std::unordered_map) 使用 BTYE* 作为键。传入的两个指针明显不同。您似乎计算的哈希值被放入映射的,而不是它的键。

虽然有时使用指针作为键很有用,但您通常希望使用值类型,例如std::vector&lt;BYTE&gt;,作为键。

【讨论】:

  • ` std::hash_map<:vector>,std::string> table1; std::pair<:vector>,std::string> pair1; std::vector *a=new std::vector(); std::vector::iterator iter; a->插入(a->开始(),5);对1.first=*a; pair1.second="noname"; table1.insert(pair1);` 在这样简单的代码中,它说不能将 vector<_ty> 转换为 size_t
  • 这只是表示没有std::vector&lt;T&gt;的默认哈希函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 2013-02-16
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
相关资源
最近更新 更多