Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 4th, 2012  |  syntax: None  |  size: 1.36 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to write this for-loop using std::for_each or std::transform?
  2. vector<vector<int> > int_vectors;
  3.  
  4. // ... fill int_vectors
  5.  
  6. vector<int> ints;
  7.  
  8. for (vector<vector<int> >::const_iterator iter = int_vectors.begin(); iter != int_vectors.end(); ++iter) {
  9.    ints.insert(ints.end(), iter->begin(), iter->end());
  10. }
  11.        
  12. typedef std::vector<int>::iterator (std::vector<int>::*IteratorGetter)();
  13.  
  14. std::for_each(int_vectors.begin(), int_vectors.end(),
  15.     std::bind(
  16.         std::bind(
  17.             &std::vector<int>::insert<std::vector<int>::iterator>,
  18.             &ints,
  19.             std::bind((IteratorGetter)&std::vector<int>::end, &ints),
  20.             _1,
  21.             _2
  22.         ),
  23.         std::bind((IteratorGetter)&std::vector<int>::begin, _1),
  24.         std::bind((IteratorGetter)&std::vector<int>::end, _1)
  25.     )
  26. );
  27.        
  28. typedef std::vector<int> VI;
  29. typedef std::vector<VI> VVI;
  30.  
  31. VVI int_vectors;
  32. VI ints;
  33.  
  34. std::for_each(int_vectors.begin(), int_vectors.end(), [&](VI &vec) {
  35.     ints.insert(ints.end(), vec.begin(), vec.end());
  36. });
  37.        
  38. #include <algorithm>
  39. #include <vector>
  40. #include <iostream>
  41. #include <iterator>
  42.  
  43. using namespace std;
  44. #define all(v) (v).begin(), (v).end()
  45. #define foreach(it, v) for(auto it = (v).begin(); it != (v).end(); ++it)
  46.  
  47. void main() {
  48.     vector<int> vi;
  49.     vector<vector<int>> vvi;
  50.  
  51.     foreach(it, vvi) {
  52.         copy(all(*it), back_inserter(vi));
  53.     }
  54. }