本文介绍了std :: multimap :: equal_range是否可能返回不正确的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下午好,我发现 std:multimap :: equal_range 有时会返回不正确的结果。这可能吗?如果是这样,有我的代码或哈希函数的指针的解决方法或一些错误。谢谢。

Good afternoon, I am finding that std:multimap::equal_range returns incorrect results sometimes. Is this possible? If so, is there a workaround or some error in my code or hash function for pointers. Thank you.

以下是我的代码摘录:

typedef std::multimap<char *,Range>::const_iterator I;
std::pair<I,I> b = mmultimap.equal_range(TmpPrevMapPtr);
for (I i=b.first; i != b.second; ++i){
    ranges_type.erase(i->second);
}
erasecount = mmultimap.erase(TmpPrevMapPtr);

其中mmultimap具有散列指针键和范围值。类范围如下:

where mmultimap has a hashed pointer key and a Range value. The class Range looks like this:

class Range { 
public:   
    explicit Range(int item){// [item,item] 
      mLow = item;
      mHigh = item;
      mPtr  = 0;
      mMapPtr = 0;
      mStamp = 0;
    }

    Range(int low, int high, char* ptr = 0,char* mapptr, int stamp){  
      mLow = low;
      mHigh = high;
      mPtr  = ptr;
      mMapPtr = mapptr;
      mStamp = stamp;
    }        

    int low() const { return mLow; }   
    int high() const { return mHigh; }
    char* getPtr() const { return mPtr; }
    char* getMapPtr() const { return mMapPtr; }
    int getStamp() const { return mStamp; }

private:   
    int mLow;   
    int mHigh; 
    char* mPtr;
    char* mMapPtr;
    int mStamp;
}; // class Range 


推荐答案

c> char * 相等的指针,当你想比较C字符串。你需要提供一个比较函数到multimap或(更好地)使用std :: string。考虑下面的程序,注意 A1 != A2 ,但 strcmp )== 0

You are comparing char* pointers for equality, when you want to compare C strings. You need to supply a comparison functor to multimap or (better yet) use std::string. Consider the following program and note how A1 != A2, but strcmp(A1, A2)==0.

#include <map>
#include <string>
#include <cstring>
#include <iostream>

struct compare {
 bool operator()(char *left, char *right) const {
  return std::strcmp(left,right) < 0;
 }
};


int main() {
  char A1[] = "A";
  char A2[] = "A";

  std::multimap<char*, int> bad;
  bad.insert(std::pair<char*,int>(A1, 1));
  bad.insert(std::pair<char*,int>(A2, 1));
  std::cout << bad.count("A") << ", " << bad.count(A1) << "\n";

  std::multimap<char*, int, compare> good;
  good.insert(std::pair<char*,int>(A1, 1));
  good.insert(std::pair<char*,int>(A2, 1));
  std::cout << good.count("A") << ", " << good.count(A1) << "\n";

  std::multimap<std::string, int> better;
  better.insert(std::pair<std::string,int>(A1, 1));
  better.insert(std::pair<std::string,int>(A2, 1));
  std::cout << better.count("A") << ", " << better.count(A1) << "\n";
}

这篇关于std :: multimap :: equal_range是否可能返回不正确的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 04:38