Reputation: 1288
I wrote a small function whose aim is to go through a list of elements in order, do some checks on the hashmap value of it and if they pass, return it.
QString ElementContainer::getPreferedAvailableElement() const
{
QStringList preferred_priority = { A, B, C, D, E };
foreach(QString element, preferred_priority){
Element* data = m_hashmap.value(element, nullptr);
if(data && data->isReady()){
return element;
}
}
return QString("");
}
I know that those functional kind of std functions should not be forced no matter if it makes sense or not. I am just curious how you can transform this and if it maybe is more verbose.
Upvotes: 1
Views: 76
Reputation: 8427
You can use std::find_if
like this:
QString ElementContainer::getPreferedAvailableElement() const
{
QStringList preferred_priority = { A, B, C, D, E };
auto it = std::find_if(preferred_priority.begin(),
preferred_priority.end(),
[this](const QString & element)
{
Element* data = m_hashmap.value(element, nullptr);
return (data && data->isReady());
});
if (it != preferred_priority.end())
{
return *it;
}
return QString("");
}
Upvotes: 2