fork(8) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. int main()
  6. {
  7. std::vector<int> vect { 0, 1, 2, 3, 5, 8 };
  8.  
  9. // List of subvectors extracted from 'vect'.
  10. // Initially populated with a single vector containing
  11. // the first element from 'vect'.
  12. //
  13. std::vector<std::vector<int>> sub_vectors(1, std::vector<int>(1, vect[0]));
  14.  
  15. // Iterate over the elements of 'vect',
  16. // skipping the first as it has already been processed.
  17. //
  18. std::for_each(vect.begin() + 1,
  19. vect.end(),
  20. [&](int i)
  21. {
  22. // It the current int is one more than previous
  23. // append to current sub vector.
  24. if (sub_vectors.back().back() == i - 1)
  25. {
  26. sub_vectors.back().push_back(i);
  27. }
  28. // Otherwise, create a new subvector contain
  29. // a single element.
  30. else
  31. {
  32. sub_vectors.push_back(std::vector<int>(1, i));
  33. }
  34. });
  35.  
  36. for (auto const& v: sub_vectors)
  37. {
  38. for (auto i: v) std::cout << i << ", ";
  39. std::cout << std::endl;
  40. }
  41. }
  42.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
0, 1, 2, 3, 
5, 
8,