简体   繁体   English

<运算符比较两个相同的对象时,不会插入QMap

[英]QMap doesn't insert when < operator compares two identical objects

I'm trying to learn Qt. 我正在尝试学习Qt。 I experienced some issues but generally I find the solution by googling. 我遇到了一些问题,但通常可以通过谷歌搜索找到解决方案。 But this afternoon I had an issue with QMap and I don't understand the problem. 但是今天下午我遇到了QMap的问题,我不明白这个问题。

I've created a class File and I overrided the operator< in order to be able to use it as key in QMap<File, bool> . 我创建了一个File类,并重写了operator< ,以便能够将其用作QMap<File, bool> The issue is that when I try to initialize a QMap by inserting entries the file map doesn't contain a duplicate entry in the sense of the implementation of the operator< . 问题是,当我尝试通过插入条目来初始化QMap ,就operator<的实现而言,文件映射不包含重复的条目。

 bool File::operator<(const File &file) const{
   if(comparator == NAME){
     if(this->getFileName() != file.getFileName()){
        return this->getFileName() < file.getFileName();
     }
     return false;
   }
   return this->getFileHash() < file.getFileHash();
}

QMap initialization: QMap初始化:

for(File file: files){
    //filesCheckStatus edclared in the header file QMap<File, bool> filesCheckStatus;
    filesCheckStatus.insert(file, false);
}

In this example when comparator NAME is used entries with the same name ( QString ) are inserted only once. 在此示例中,当使用比较器NAME时,具有相同名称( QString )的条目仅插入一次。

In case I return false in all cases the final map contains only one entry (the first inserted). 如果我在所有情况下都返回false,则最终映射仅包含一个条目(第一个插入的条目)。

Could someone explain this behavior? 有人可以解释这种行为吗?

In this example when comparator NAME is used entries with the same name (QString) are inserted only once. 在此示例中,当使用比较器NAME时,具有相同名称(QString)的条目仅插入一次。

That's how maps and sets work. 这就是映射和设置的工作方式。 Each key is unique[1] in the collection. 每个键在集合中都是唯一的[1]。 If you want multiple File s that compare the same, you could use QMultiMap<File, bool> , or QVector<std::pair<File, bool>> . 如果要比较多个File ,可以使用QMultiMap<File, bool>QVector<std::pair<File, bool>>

In case I return false in all cases the final map contains only one entry (the first inserted). 如果我在所有情况下都返回false,则最终映射仅包含一个条目(第一个插入的条目)。

That's because the ordering that defines compares everything as equivalent to everything else. 这是因为定义的顺序会将所有内容等同于其他所有内容进行比较。

  1. Unique under the equivalence relation !(a < b) && !(b < a) . 在等价关系!(a < b) && !(b < a)下是唯一的。 More generally for a binary predicate comp , you have a binary predicate equiv that is defined by equiv(a, b) = !comp(a, b) && !comp(b, a) 更一般而言,对于二元谓词comp ,您具有由equiv(a, b) = !comp(a, b) && !comp(b, a)定义的二元谓词equiv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM