Qt-将自定义类作为键的QMap

Qt-将自定义类作为键的QMap,qt,qmap,Qt,Qmap,我有一个QMap,其中有一个自定义类作为键,但是当我尝试插入具有不同键的元素时,有时映射会替换另一个元素。 就我而言,问题在于: #include <QCoreApplication> #include <QMap> #include <QDebug> class A { public: A(int value, const QString& string) { m_value = value; m_string = string; }

我有一个QMap,其中有一个自定义类作为键,但是当我尝试插入具有不同键的元素时,有时映射会替换另一个元素。 就我而言,问题在于:

#include <QCoreApplication>
#include <QMap>
#include <QDebug>

class A
{
  public:
    A(int value, const QString& string) { m_value = value; m_string = string; }

    bool operator<(const A& other) const { return m_value < other.m_value && m_string < other.m_string; }

  private:
    int m_value;
    QString m_string;
};

int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);

  QMap<A, QString> map;

  map.insert(A(10, "ONE"), "FIRST");
  map.insert(A(10, "TWO"), "SECOND");
  map.insert(A(20, "THREE"), "THIRD");

  return 0;
}
#包括
#包括
#包括
甲级
{
公众:
A(int-value,const-QString&string){m_-value=value;m_-string=string;}

布尔运算符您对
运算符的定义中有错误您对
运算符的定义中有错误您是否尝试向类中添加赋值运算符?我已尝试添加赋值和相等运算符,但QMap使用运算符您是否尝试向类中添加赋值运算符?我已尝试添加赋值运算符和相等运算符但QMap使用运算符你是对的,我应该在运算符no中使用| |而不是&,这仍然是错误的。我发现比较结构的一个好方法是添加一个从结构中创建std::tuple的方法,然后比较这些元组。你是对的,我应该在运算符no中使用| |而不是&,这仍然是错误的。我&比较结构的一个好方法是添加一个从结构中创建std::tuple的方法,然后比较这些tuple。
map.insert(A(10, "ONE"), "FIRST");    // insert first element
map.insert(A(10, "TWO"), "SECOND");   // put value `SECOND` in the found key
map.insert(A(20, "THREE"), "THIRD");  // put second element
bool operator<(const A& other) const {
    if (m_value < other.m_value) return true;
    return m_string < other.m_string;
}