Hacker News new | past | comments | ask | show | jobs | submit login

I think people sometimes feel compelled to combine auto and the range based for loop when they shouldn't. In this example the range based for loop adds clarity but the use of auto doesn't. I would have written something like:

    for(const string &s : data) {
        ofile << s << std::endl;
    }
which is a lot more clear about what type of thing you're getting out of the vector on each iteration.



Actually, the only thing this tells you about what you are getting out of the vector is that it can be implicitly converted to a string.

If data is a vector of, for example, pointers to const char, on each iteration this code will unnecessarily copy each item into a temporary string before printing it. Using auto would avoid this step, regardless of data's type.

Note that the typical non-range-based for loop also omits the vector item type... Is this that much less clear?:

  for (int i = 0; i < data.size(); ++i) {
      ofile << data[i] << std::endl;
  }


That's a good point, but when I think of the typical code for non-range-based for loop it looks like:

    for (vector<string>::iterator i = data.begin(); i != data.end(); ++i) {
        ofile << *i << std::endl;
    
    }
which makes it pretty clear what types we're dealing with.


I think in C++1y we'll be able to define a function 'foreach' that we can use like:

    foreach(data, []<class T>(const T & item) {
        ofile << item << std::endl;
    });
This should eliminate the potential implicit conversion to temp. But I'm not sure it's seriously better than the original range based for with auto.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: