Search code examples
c++c++11for-loopstlidioms

For-loop or std::any_of, which one should I use?


I can't decide between a for-loop and std::any_of, e.g:

QString fileName = "Whatever";  // might contain a key-string which is part of sMyStringlist()
auto anyTypeContains = [&](const QString& categoryStr)
{
    for(auto const &keyStr : sMyStringlist()[categoryStr])
        if(fileName.contains(keyStr, Qt::CaseInsensitive))
            return true;
    return false;
};
if(anyTypeContains("myCategory"))
...

or

QString fileName = "Whatever";  // might contain a key-string which is part of sMyStringlist()
auto anyTypeContains = [&](const QString& categoryStr)
{
    return std::any_of(
                sMyStringlist()[categoryStr].begin(),
                sMyStringlist()[categoryStr].end(),
                [&](const QString& keyStr){
        return fileName.contains(keyStr, Qt::CaseInsensitive);
    });
};
if(anyTypeContains("myCategory"))
...

I think the for-loop might be better since everyone should be familiar with it. Is there any reason for using any_of or is it just a matter of taste? Are there other (better) alternatives? Thanks in advance.


Solution

  • Many C++ standard library functions (typically those in <algorithm>) are there to obviate the need for for or other loop constructs. std::accumulate is an early example.

    Therefore prefer std::any_of rather than a loop.