For loops against standard library algorithms with a relatively old compiler

I know that code is better if there are no confusing loops in it for. And it is always useful to reuse standard library algorithms whenever possible. However, I find that the syntax of iterators and algorithms looks very confusing.

I want to give a real life example from my current project: I want to copy the contents vector<vector<QString>> into vector<QVariant> out. I do not see the difference between:

for (int i = 0; i < in[0].size(); i++ ) 
{ 
    if(in[0][i].isNull() || in[0][i].isEmpty() ) 
        out[i] = "NONE";
    else
        out[i] = in[0][i];
}

So what:

std::transform(in[0].begin(), in[0].end(), out.begin(), [](const QString& a)->QVariant{
    if(a.isNull() || a.isEmpty() ) 
        return "NONE";
    else
        return a;
}); 

Since we have visual studio 2012, I even need to enter the return value of my lambda. After using ranges such as:

in[0].map!( a => a.isNull() || a.isEmpty() ? "NONE" : a ).copy(out);

D std::transform . , , for. : std::transform , for?

+4
2

, , , transform - .

, , , std::replace_copy_if, ( ) .

Qt, , QVariant QString std::vector<std::string>, , Qt.

#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <string>

int main() {   
    std::vector<std::string> input { "one", "two", "", "three" };
    std::vector<std::string> output;

    // copy input to output, replacing the appropriate strings:
    std::replace_copy_if(input.begin(), input.end(),
                         std::back_inserter(output),
                         [](std::string const &s) { return s.empty(); }, 
                         "NONE");

    // and display output to show the results:
    std::copy(output.begin(), output.end(),
              std::ostream_iterator<std::string>(std::cout, "\n"));
}

NONE, ( , isNull , ).

, , , :

one
two
NONE
three

, , . , , () input.begin(), input.end() input. , -, , D, , , , ( ).

, range, : Boost Range , ( , ) Eric Neibler.

+8

? : ( static QVariant QVNone;, ).

std::transform(in[0].begin(), in[0].end(), out.begin(),
               [](const QString& a)   // for C++14: (auto& a)
                  { return a.isNull() || a.isEmpty() ? QVariant("NONE") : a; }
              );

: QVariant(const QString&), ? : .

++ 11 , return - . (3) . ++ 14 ala (auto& a). ; , ++ 17; .

() ++, , , D. , Google .

+3

All Articles