c++ - 使用 std::string 作为 std::map 的键

标签 c++ string stl map

我想要一个 std::map (int .NET 4.0)。我们当然知道 map 是一棵树,并且需要一个 operator< 字符串没有为我们定义。

Error 24 error C2676: binary '<' : 'const std::string' does not define this operator or a conversion to a type acceptable to the predefined operator c:\program files\microsoft visual studio 10.0\vc\include\xfunctional 125 1 FXCMMarketDataServer

所以我让我的 google-foo 工作并找到了这个解决方案:

struct StringComparerForMap
{
public:
    bool operator()(const std::string x, const std::string y)
    {
         // Add compare logic here
    }
};

...
std::map<std::string, CustomObject, StringComparerForMap> myMap;

这在一段时间内工作得很好,现在我遇到了一个我认为是由于这个原因的错误。在 STL 框架的某个深处,它似乎忽略了上述定义并默认为 operator<.

在 VS2010 .NET 4.0 中有没有办法使用字符串作为映射的键?

我知道我可以获取该字符串并编写一个函数将其散列为一个 int,但其中的乐趣在哪里?

编辑

我会尽力为大卫解释这一点。当映射使用比较器结构时,它会在发布时崩溃,并在调试中使调试断言失败。失败的断言在 xtree 第 1746 行。

Expression: invalid operator<

|Abort| |Retry| |Ignore|

这让我相信,尽管给 map 一个比较器,但它仍然在某些路径下默认为 operator< 进行比较。我的代码中导致这种情况的行是:

CustomObject o = stringObjectMap[key];

最佳答案

Error 24 error C2676: binary '<' : 'const std::string' does not define this operator or a conversion to a type acceptable to the predefined operator c:\program files\microsoft visual studio 10.0\vc\include\xfunctional 125 1 FXCMMarketDataServer

这就是当你忘记包含 <string> 时 VC 吐在你脸上的东西.该 header 明确定义了此运算符。

关于c++ - 使用 std::string 作为 std::map 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4939204/

相关文章:

c++ - 什么决定了我的可执行文件的大小?

c++ - 使用 RTTI(或返回类型标签的虚函数)是否可行?

C++ 自定义数组容器动态大小

java - 按下按钮时生成随机句子,代码看起来正确但不起作用

c++ - 非 B 树数据结构,其中昆虫以排序的方式完成,但我可以稍后从随机位置删除对象

c++ - 头文件中定义的const float**

java - 如何解析一个字符串与另一个字符串的比较?

c++ - 是否可以将虚函数和函数对象混合使用 std 算法?

c++ - std::for_each 优于 std::set,C++11

python - 如何删除列表开头和结尾的空白元素 Python