【问题标题】:C ++ Issue with map and the Compare Class地图和比较类的 C++ 问题
【发布时间】:2012-11-06 21:57:16
【问题描述】:

我希望也许有人可以帮助我解决我的问题。我得到了一个可爱的

没有匹配函数调用类型为“const pCompare”的对象

struct pCompare
 {
    bool operator()( const std::string & str1, const std::string & str2 ) const
    {
        return str1.compare( str2 ) == 0;
    }
 };
 std::string *t = new std::string ( "/test.html" );
 std::map<std::string*, std::string, pCompare> test;
 test.insert ( std::pair<std::string*, std::string> ( t, "héhé" ) );
 std::cout << test.find(new std::string ("/test.html") )->second;

感谢您的帮助!

【问题讨论】:

  • 您的地图有 (const) string * 作为键,但您的比较器采用 const string &amp;...
  • 是否可以将您的实现更改为使用std::map&lt;std::string, std::string&gt;。使用值而不是指针可以使事情变得更容易。
  • 另请注意,比较器应测试排序不相等,否则您将进入 UB 领域。

标签: c++ pointers map


【解决方案1】:

首先,不要这样做,因为它会搞砸您的地图:您需要地图的排序函数,而不是相等性测试。

无论如何,我猜你的问题是你的键类型 std::string* 但你的函数测试 string& 。我还没有尝试过,但这应该可以解决问题:

bool operator()( std::string * str1, const std::string * str2 ) const
{
    return *str1 < *str2;
}

【讨论】:

  • 我确实忘记了地图的树形部分,我的错……无论如何,参考是问题
猜你喜欢
  • 1970-01-01
  • 2018-04-20
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多