简体   繁体   中英

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

I'm trying to learn 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.

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> . 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< .

 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:

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.

In case I return false in all cases the final map contains only one entry (the first inserted).

Could someone explain this behavior?

In this example when comparator NAME is used entries with the same name (QString) are inserted only once.

That's how maps and sets work. Each key is unique[1] in the collection. If you want multiple File s that compare the same, you could use QMultiMap<File, bool> , or QVector<std::pair<File, bool>> .

In case I return false in all cases the final map contains only one entry (the first inserted).

That's because the ordering that defines compares everything as equivalent to everything else.

  1. Unique under the equivalence relation !(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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