gpt4 book ai didi

c++ - 是否可以将 QColor 作为键存储在 QMap 中

转载 作者:太空狗 更新时间:2023-10-29 20:23:34 28 4
gpt4 key购买 nike

所以,我有简单的代码

QMap<QColor, int> colors;
for(int w = 0; w < image.width(); ++w)
for (int h = 0; h < image.height(); ++h)
colors[QColor::fromRgb(image.pixel(w,h))]++;

错误信息是

no match for 'operator<' (operand types are 'const QColor' and 'const QColor').

因此,qMapLessThanKey 尝试实例化两种颜色的比较器未成功,这是不可能的。

问题是:是否可以将 QColor 作为键作为值而不是通过引用存储在 QMap 中?

只是好奇。我知道如何用其他方式写出我想要的东西。但令我感到奇怪的是,在 QT 中对于我可以存储在 map 中或不能存储的内容有任何异常(exception)。

最佳答案

不,因为 QColor doesn't provide operator< ,即 required通过 QMapKey输入:

The key type of a QMap must provide operator<() specifying a total order.

一个选项是定义 operator<对于 QColor你自己,但我不建议这样做,因为我不确定它是否应该被定义。

我建议只使用 std::map使用自定义比较器(第三个模板参数):

struct color_compare {
bool operator()(QColor const&, QColor const&) { /* ... */ }
};

std::map<QColor, Value, color_compare> map;
// ...

关于c++ - 是否可以将 QColor 作为键存储在 QMap 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512125/

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