Range-based loop, STL algorithms

Welcome,

When range-loop came into picture, I've started using it as soon as I could. As a programmer I'm looking for the simplest solution, which covers the problem, do the test and deploy. Let then the Computer do the dirty work! I'm its master! ;)

A person always looking for a better solution. A programmer is looking for a more simpler one, because over time, the code will be a subject of a rewrite or refactor (I still hear the screaming of managers, caused by these words ;)

Next is a source code for a range-loop method and an STL algorithm. They do the same thing, but looks a bit different. (We can also look at the code of those STL templates, and we'll find those for's ;)

This is a simple example, which not based on any real life story:

#include <iostream>

int main()
{
    int a;
    a = 5;
    std::cout << a << std::endl;
};
#include <QString>

struct MyStruct 
{ 
MyStruct(int id, QString text) 
    : _id(id) 
    , _text(text)
{
}

    int _id; 
    QString _text; 
};

At this point we have a struct declaration, which will plays as a key-value container on later. (Why is it key-value container then? that would be too simple ;)

Time to use our declaration, and set up some goals:

#include <QList>

int main(int argc, char *argv[])
{
    // key-value pairs
    QList<MyStruct> _myNumbers = {MyStruct("0", "null"),};
    
    // request
    QList<int> _requests = {3, 5, 8};

    // result
    QList<QString> _result;

    // this is the place of solution code
        
    return 0;
}

The task is the following. Lookup each number from _requests within _myNumbers, and append a copy of the corresponding MyStruct's _text value to _results. (You are right! this job do not need a computer! this can be solved on a squared paper. believe me, there are simpler things are in this world which already programmed by big-BIG companies. :)

I'll first create a range-loop solution:

for (auto& item : _requests)
{
    for (auto& elem : _myNumbers)
    {
        if (elem._id == item)
        {
            _result.append(elem._text);
            break;
        }
    }
}

Next the same goal, but simpler! :D

_result = std::accumulate(_requests.begin(), _requests.end(), QList<QString>{}, [this](auto& a, int item){
    auto it = std::find_if(_myNumbers.begin(), _myNumbers.end(), [item](auto& elem){
        return elem.id == item;
    });

    if (it == this->_detail.end())
        a.append(QString("No number like this one: %1").arg(item));
    else
        a.append(it->text);

    return a;
});

Most of the range-loops could be replaced by with STL algorithms. Why is it good for? (for? I mean why is it good to use STL? ;)

Conclusion:

  • The code will be more clear to others. The STL algorithms operations are obvious. Any container manipulation could be feasible.
  • Simpler to maintain. As we check this code parts, we surely know what the original author wants to do. Many for-loops could not be simple to understand
  • Easier bug fix. We could trust in STL code, which helps us reduce the error opportunities. (I know, we don't trust in STL at all! Just in ourselves! :)

 

I hope this article helps, and leads to refactor! (oh nooo, those screaming voices again... :)

 

 

 

Headline: 
Compare of range-based loop and STL algorithms
Date modified: 
Friday, December 16, 2016 - 00:15
Date published: 
Main entity of page: 
https://www.gepardorm.eu/content/range-based-loop-stl-algorithms
Keywords: 
C++, example, tutorial, STL, Range-based loop, Lambda, std::accumulate
Author: