所以,我有简单的代码
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))]++;错误信息是
不匹配“operator<”(操作数类型为“const QColor”和“const QColor”)。
因此,qMapLessThanKey试图实例化两种颜色的比较器,但没有成功,这是不可能的。
的问题是:是否可以将QColor作为值而不是引用存储在QMap中?
只是好奇而已。我知道怎么用另一种方式写我想要的东西。但让我感到奇怪的是,QT中有任何例外,我可以存储在地图中,或者不能存储。
发布于 2015-09-10 21:54:42
不,因为operator<是QMap的Key类型的必填项:
QMap的键类型必须提供指定总顺序的operator<()。
一种选择是自己为operator<定义QColor,但我不建议它,因为我不确定它是否应该被定义。
我建议只对自定义比较器(第三个模板参数)使用std::map,如下所示:
struct color_compare {
bool operator()(QColor const&, QColor const&) { /* ... */ }
};
std::map<QColor, Value, color_compare> map;
// ...发布于 2015-09-11 14:15:25
当然有可能。这是一个缺少的Qt特性。您可以自己实现比较操作符,按字典顺序比较R、G、B、A值:
// https://github.com/KubaO/stackoverflown/tree/master/questions/qmap-qcolor-32512125
#include <QtGui>
bool operator<(const QColor & a, const QColor & b) {
return a.redF() < b.redF()
|| a.greenF() < b.greenF()
|| a.blueF() < b.blueF()
|| a.alphaF() < b.alphaF();
}
int main() {
Q_ASSERT(QColor(Qt::blue) < QColor(Qt::red));
Q_ASSERT(QColor(Qt::green) < QColor(Qt::red));
Q_ASSERT(QColor(Qt::blue) < QColor(Qt::green));
Q_ASSERT(! (QColor(Qt::red) < QColor(Qt::red)));
QMap<QColor, int> map;
map.insert(Qt::red, 0);
map.insert(Qt::green, 1);
map.insert(Qt::blue, 2);
Q_ASSERT(map.size() == 3);
Q_ASSERT(map.cbegin().key() == Qt::red);
Q_ASSERT((map.cbegin()+1).key() == Qt::green);
Q_ASSERT((map.cbegin()+2).key() == Qt::blue);
}https://stackoverflow.com/questions/32512125
复制相似问题