code_junkie

STL non-copying wrapper around an existing array?

Nov 11th, 2011
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. int ary[100];
  2. // init ...
  3.  
  4. std::sort(ary, ary+100); // sorts the array
  5. std::find(ary, ary+100, pred); find some element
  6.  
  7. int a[100];
  8. for (int i = 0; i < 100; ++i)
  9. a[i] = 0;
  10.  
  11. boost::array<int,100> a;
  12. for (boost::array<int,100>::iterator i = a.begin(); i != a.end(); ++i)
  13. *i = 0;
  14.  
  15. #include <algorithm>
  16. #include <iostream>
  17. #include <iterator>
  18.  
  19. int main()
  20. {
  21. int data[] = {4,3,7,5,8};
  22. std::sort(data,data+5);
  23.  
  24. std::copy(data,data+5,std::ostream_iterator<int>(std::cout,"t"));
  25. }
  26.  
  27. template <typename T, int I>
  28. inline T * array_begin (T (&t)[I])
  29. {
  30. return t;
  31. }
  32.  
  33. template <typename T, int I>
  34. inline T * array_end (T (&t)[I])
  35. {
  36. return t + I;
  37. }
  38.  
  39. void foo ()
  40. {
  41. int array[100];
  42. std::find (array_begin (array)
  43. , array_end (array)
  44. , 10);
  45. }
  46.  
  47. struct Bob
  48. { int val; };
  49.  
  50. bool operator<(const Bob& lhs, const Bob& rhs)
  51. { return lhs.val < rhs.val; }
  52.  
  53. // let's do a reverse sort
  54. bool pred(const Bob& lhs, const Bob& rhs)
  55. { return lhs.val > rhs.val; }
  56.  
  57. bool isBobNumberTwo(const Bob& bob) { return bob.val == 2; }
  58.  
  59. int main()
  60. {
  61. Bob bobs[4]; // ok, so we have 4 bobs!
  62. const size_t size = sizeof(bobs)/sizeof(Bob);
  63. bobs[0].val = 1; bobs[1].val = 4; bobs[2].val = 2; bobs[3].val = 3;
  64.  
  65. // sort using std::less<Bob> wich uses operator <
  66. std::sort(bobs, bobs + size);
  67. std::cout << bobs[0].val << std::endl;
  68. std::cout << bobs[1].val << std::endl;
  69. std::cout << bobs[2].val << std::endl;
  70. std::cout << bobs[3].val << std::endl;
  71.  
  72. // sort using pred
  73. std::sort(bobs, bobs + size, pred);
  74. std::cout << bobs[0].val << std::endl;
  75. std::cout << bobs[1].val << std::endl;
  76. std::cout << bobs[2].val << std::endl;
  77. std::cout << bobs[3].val << std::endl;
  78.  
  79. //Let's find Bob number 2
  80. Bob* bob = std::find_if(bobs, bobs + size, isBobNumberTwo);
  81. if (bob->val == 2)
  82. std::cout << "Ok, found the right one!n";
  83. else
  84. std::cout << "Whoops!n";
  85.  
  86. return 0;
  87. }
Add Comment
Please, Sign In to add comment