0
votes

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?

1
It's how maps and sets work - a key can appear only once. - rustyx
Try QMultiMap - Felix
File is the key not the file name which is a field of File and == is not used to ensure using unique keys (like equals in java). - naslami

1 Answers

0
votes

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 Files 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)