C++ Aware 复制插入到 std::map

标签 c++ hash insert duplicates stdmap

我有一个关于在 C++ 中向 std::map 插入内容的问题。

这就是我的代码:

stringutils.hh:

...

  unsigned long hashSDBM(char *strToHash){
      unsigned char* str = new unsigned char[strlen(strToHash) + 1];
      strncpy( (char *) str, strToHash, strlen(strToHash) );

      unsigned long hash = 0;
      int c;

      while ((c = *str++)){
          hash = c + (hash <<6) + (hash <<16) - hash;
      }

      return hash;
  }

...

哈希表.hh

#include "stringutils.hh"

namespace{

using namespace std;

class MapElement{

    private:
        char* filename;
        char* path;

    public:
        MapElement(char* f, char* p):filename(f), path(p){}
        ~MapElement(){
           delete [] filename;
           delete [] path;
        }
        char* getFileName(){ return filename; }
        char* getPath(){ return path; }

};


class HashMap{

    private:
        map<long*, MapElement*> *hm;

        long hash(char* key);

    public:
        HashMap(){
           hm = new map<long*, MapElement*>();
        }
        ~HashMap(){
           delete hm;
        }
        long put(char* k, MapElement *v);
};

long HashMap::hash(char* key){
  return stringutils::hashSDBM(key);
}


long HashMap::put(char* k, MapElement *v){
  long *key = new long();
  *key = hash(k);
  pair<map<long*,MapElement*>::iterator, bool> ret;
  ret = hm->insert(std::pair<long*, MapElement*>(key, v));

  if(ret.second == false){
    cerr<<"Already exists: "<<ret.first->second->getFileName()<<endl;
    return *key;
  }
  cerr<<"INSERTED "<<*key<<endl;
  return 0;
}

主.cc:

HashMap *hm = new HashMap();


int main(void){

  MapElement *m1; 

  char a[] = "hello";
  char b[] = "world";
  m1 = new MapElement(a,b);
  hm->put(a, m1);

  char c[] = "thats";
  char d[] = "a test";
  m1 = new MapElement(c,d);
  hm->put(c, m1);

  char e[] = "hello";
  char f[] = "test";
  m1 = new MapElement(e,f);
  hm->put(e, m1);

  return 0;
}

它编译时没有任何错误或警告,当我启动它时,会生成以下输出:

已插入 7416051667693574450

已插入 8269306963433084652

已插入 7416051667693574450

为什么第二个插入键“hello”没有任何效果?

最佳答案

std::map 中的键是唯一的。如果要允许重复键,请使用 std::multimap。您正在使用的 map::insert 返回一对迭代器和一个 bool。 bool 指示插入是否实际插入(如果键已经存在则不是)。

关于C++ Aware 复制插入到 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12678796/

相关文章:

ruby - 按值的长度对散列进行排序(降序)

java - 如何在递归中做一次性的事情?

mongodb - 在Go中使用mgo找出插入对象的结果

c++ - 转到特定页面后,如何将SwipeView的currentIndex设置为TabBar的currentIndex "by reference"?

c++ - 使用 pybind11 在类方法中调用嵌入函数

c++ - 代码块宏

c++ - 针对特定后端的 Boost.Locale 测试

c++ - 对 "class"的引用不明确

ruby - 如何仅基于键从哈希数组中删除重复项?

mysql - 如何在mysql存储过程中使用insertignore