3 ms·
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
by jcl 13y ago
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;
}
- minimax 13y agoThat'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.
- marshray 13y agoI 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.