c++ - For loops vs standard library algorithms with a relatively old compiler -


i know code better when there not confusing for loops in it. , reuse standard library algorithms when possible. however, find syntax of iterators , algorithms looks confusing.

i want give real life example current project: want copy contents of vector<vector<qstring>> in vector<qvariant> out. can't see difference between:

for (int = 0; < in[0].size(); i++ )  {      if(in[0][i].isnull() || in[0][i].isempty() )          out[i] = "none";     else         out[i] = in[0][i]; } 

and that:

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 have visual studio 2012 have type return value of lambda. after using ranges like:

in[0].map!( => a.isnull() || a.isempty() ? "none" : ).copy(out); 

in d language can't live std::transform code above. , not sure whether better basic for loop. question is: code using std::transform above better for loop?

at least in opinion, main problem here transform wrong tool job.

what you're trying std::replace_copy_if does, (no big surprise) lot more neatly.

i don't have qt installed on machine @ hand, took liberty of replacing qvariant , qstring code std::vector<std::string>, believe same basic idea should apply qt types well.

#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 output, replacing appropriate strings:     std::replace_copy_if(input.begin(), input.end(),                          std::back_inserter(output),                          [](std::string const &s) { return s.empty(); },                           "none");      // , display output show results:     std::copy(output.begin(), output.end(),               std::ostream_iterator<std::string>(std::cout, "\n")); } 

for moment, replaces empty strings none, adding null check should pretty trivial (with type isnull meaningful, of course).

with data above, result you'd expect:

one 2 none 3 

i should add, however, pretty verbose. nice when @ least have ranges added standard library, (for example) input.begin(), input.end() can replaced input. result still won't terse d code gave, @ least reduces verbosity (and same applies other algorithms well).

if care that, there couple of range libraries might want at--boost range one, , (much more interesting, in opinion) eric neibler's range library.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -