Reputation: 7974
I need to check if a QSet
contains a certain value and if it is not there, I want to insert it and return a boolean value indicating whether the value was inserted (true
) or whether it had already been there (false
). My question is how to do this efficiently. The following code actually calculates the hash and searches the set two times. This is very inefficient.
QSet<QString> names;
bool inserted = false;
QString name = "Dave";
if (!names.contains(name))
{
inserted = true;
names.insert(name);
}
Upvotes: 6
Views: 1450
Reputation: 7974
OK, immediately after I posted the question I realized this is very easy. Anyway, I think I will keep the question for others.
int size = names.count();
names.insert(name);
bool inserted = names.count() > size;
Upvotes: 7