Reputation: 218
I am trying to write a function to determine if a given isbn number is in a QMap
list, I see I'm not using contains
properly, not sure if this would even logically work?
bool TextbookMap::foundTextBook(QString isbn) const {
bool found = false;
ConstIterator itr = constBegin();
for ( ; itr != constEnd(); ++itr)
{
if (itr.contains(isbn))
found = true;
}
return found;
}
Upvotes: 1
Views: 637
Reputation: 36649
You do not need to iterate the map - this is what contains()
already does for you. Simply use
bool TextbookMap::foundTextBook(const QString& isbn) const {
return contains(isbn);
}
(I assume that you have derived TextbookMap
from QMap
)
The below code prints
false
true
class Textbook {
};
class TextbookMap : public QMap<QString, Textbook*> {
public:
bool foundTextBook(const QString& isbn) const;
};
bool TextbookMap::foundTextBook(const QString& isbn) const {
return contains(isbn);
}
int main(int argc, char ** argv) {
TextbookMap map;
map.insert("1234", new Textbook());
map.insert("5678", new Textbook());
qDebug() << map.foundTextBook("01234");
qDebug() << map.foundTextBook("1234");
return 0;
}
In this example, you do not even need to implement a separate method - you could also use map.contains()
directly. But it depends on your concrete requirements whether it makes sense to encapsulate the contains()
method like this. On a side note, I usually try to avoid deriving from container classes and use delegation instead.
Upvotes: 5