gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:02:04 24 4
gpt4 key购买 nike

我想要一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com