Reputation: 1055
I'm trying to follow the advice given, among other place, here to avoid raw loops and use std::algorithm
instead. So I would be thankful if you could help me do that, if possible, in the following case:
std::stringstream ss;
std::vector<Object> v;
for (const auto& curr : v) { ss << curr.ToString() << '\n'}
return ss.str()
Upvotes: 4
Views: 7284
Reputation: 10316
This is pretty concise:
std::copy(v.begin(), v.end(), std::ostream_iterator<Object>(std::cout, "\n"));
It would only work if operator<<
is appropriately defined, for example
std::ostream& operator<<(std::ostream& ostr, const Object& obj)
{
return ostr << obj.ToString();
}
Upvotes: 5
Reputation: 33116
I'm trying to follow the advice given, among other place, here to avoid raw loops and use std::algorithm instead.
Now why do you want to do that?
The example Sean Parent used in the first seven minutes or so of his talk was indeed a horrendously bad example of code. The code was terribly convoluted and it went on and on and on. However, transliterating that awful mess of multiple for
loops with nested logic within into various calls to the algorithms library would have been even worse. Parent missed the most important coding guideline of all (read with humor):
Always write your code as if the person who will be assigned to maintain it is a psychopathic blub programmer who knows where you live.
If you're a good programmer, you have to temper your desire to make your code as smart and cool and compact as can be against the fact that many other people will read your code. This tempering becomes natural when you become an excellent programmer.
I'm not saying you need to dumb your code down to the level where it becomes --C rather than C++. That said, part of being a good programmer considering the poor blub programmer who has to read and maintain that code. On you're striving to be an excellent programmer, one aims to write code that sets an example for all of code that is concise and efficient, and yet at the same time is obvious and is eminently understandable.
This might mean well mean stifling the urge to use the deepest and darkest corners of the C++ utilities, algorithms, and type traits libraries.
Upvotes: 3
Reputation: 4245
Sure, you can just run:
std::for_each(v.begin(), v.end(), [&](const Object& o) { ss << o.ToString() << '\n'; });
Which is equivalent to
for(const auto&& curr : v)
{
ss << curr.ToString() << '\n';
}
This seems like this may be a case where a loop is OK. In fact, if you look at the std::for_each
code, it just internally runs a loop, so it may be overkill.
Upvotes: 7