code_junkie

Should one prefer STL algorithms over hand-rolled loops?

Nov 11th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. #include <string>
  2. #include <iostream>
  3. #include <boost/foreach.hpp>
  4.  
  5. int main()
  6. {
  7. std::string hello( "Hello, world!" );
  8.  
  9. BOOST_FOREACH( char ch, hello )
  10. {
  11. std::cout << ch;
  12. }
  13.  
  14. return 0;
  15. }
  16.  
  17. for (int i = 0; i < some_vector.size(); i++)
  18. if (some_vector[i] == NULL) some_other_vector[i]++;
  19.  
  20. int weighted_sum = 0;
  21. for (int i = 0; i < a_vector.size(); ++i) {
  22. weighted_sum += (i + 1) * a_vector[i]; // Just writing something a little nontrivial.
  23. }
  24.  
  25. for (vector<Child>::iterator iter = children.begin();
  26. iter != children.end();
  27. ++iter)
  28. {
  29. iter->setFooCount(n);
  30. }
  31.  
  32. for_each(children.begin(), children.end(), SetFooCount(n));
  33.  
  34. class SetFooCount
  35. {
  36. public:
  37. SetFooCount(int n) : fooCount(n) {}
  38.  
  39. void operator () (Child& child)
  40. {
  41. child.setFooCount(fooCount);
  42. }
  43.  
  44. private:
  45. int fooCount;
  46. };
Add Comment
Please, Sign In to add comment