Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #include <iterator> // std::back_inserter
  2. #include <algorithm> // std::copy
  3. #include <iostream> // std::cout, std::endl
  4. #include <cstdlib> // EXIT_SUCCESS
  5. #include <vector> // std::vector
  6.  
  7. // for C++ containers
  8. template <class CC, class C>
  9. void concat (CC source_start, CC source_end, C & target) {
  10. std::back_insert_iterator<C> target_iterator = std::back_inserter(target);
  11. while (source_start != source_end) {
  12. target_iterator = std::copy(source_start->cbegin(), source_start->cend(), target_iterator);
  13. ++source_start;
  14. }
  15. }
  16.  
  17. // for C arrays
  18. // this works because C arrays are just fixed width and stored as 1d array in memory
  19. // so we can reinterpret a 2d array as a 1d array pointing to the individual elements
  20. template <typename T, size_t M, size_t N>
  21. void concat (T (& source_array)[M][N], T (& target_array)[M*N]) {
  22. T * source_array_pointer = reinterpret_cast<T *>(source_array);
  23. std::copy(source_array_pointer, source_array_pointer + M*N, target_array);
  24. }
  25.  
  26. // need a final version to deal with a subrange of an array, should be able to be done
  27. // try yourself!
  28.  
  29. int main () {
  30.  
  31. std::vector<std::vector<int>> source = { {1,2,3}, {4} };
  32. std::vector<int> target;
  33.  
  34. concat(std::begin(source), std::end(source), target);
  35.  
  36. // C arrays cannot be zig zaggy
  37. int source2[][3] = { {1, 2, 3}, {4, 5, 6} };
  38. int target2[6];
  39.  
  40. concat(source2, target2);
  41.  
  42. // can also use `char const *` as a C string
  43. const char * source3[][2] = { { "first", "second" }, { "third", "fourth" } };
  44. const char * target3[4];
  45.  
  46. concat(source3, target3);
  47.  
  48. for (auto v : target) {
  49. std::cout << v << std::endl;
  50. }
  51.  
  52. for (auto v : target2) {
  53. std::cout << v << std::endl;
  54. }
  55.  
  56. for (auto v : target3) {
  57. std::cout << v << std::endl;
  58. }
  59.  
  60. return EXIT_SUCCESS;
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement