insert.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Range v3 library
  2. //
  3. // Copyright Eric Niebler 2014-present
  4. //
  5. // Use, modification and distribution is subject to the
  6. // Boost Software License, Version 1.0. (See accompanying
  7. // file LICENSE_1_0.txt or copy at
  8. // http://www.boost.org/LICENSE_1_0.txt)
  9. #include <set>
  10. #include <vector>
  11. #include <range/v3/core.hpp>
  12. #include <range/v3/view/iota.hpp>
  13. #include <range/v3/view/take.hpp>
  14. #include <range/v3/view/for_each.hpp>
  15. #include <range/v3/view/ref.hpp>
  16. #include <range/v3/action/insert.hpp>
  17. #include "../simple_test.hpp"
  18. #include "../test_utils.hpp"
  19. template<typename T>
  20. struct vector_like : std::vector<T> {
  21. using std::vector<T>::vector;
  22. using typename std::vector<T>::size_type;
  23. size_type last_reservation{};
  24. size_type reservation_count{};
  25. void reserve(size_type n) {
  26. std::vector<T>::reserve(n);
  27. last_reservation = n;
  28. ++reservation_count;
  29. }
  30. };
  31. int main()
  32. {
  33. using namespace ranges;
  34. {
  35. std::vector<int> v;
  36. auto i = insert(v, v.begin(), 42);
  37. CHECK(i == v.begin());
  38. ::check_equal(v, {42});
  39. insert(v, v.end(), {1,2,3});
  40. ::check_equal(v, {42,1,2,3});
  41. insert(v, v.begin(), views::ints | views::take(3));
  42. ::check_equal(v, {0,1,2,42,1,2,3});
  43. int rg[] = {9,8,7};
  44. insert(v, v.begin()+3, rg);
  45. ::check_equal(v, {0,1,2,9,8,7,42,1,2,3});
  46. insert(v, v.begin()+1, rg);
  47. ::check_equal(v, {0,9,8,7,1,2,9,8,7,42,1,2,3});
  48. }
  49. {
  50. std::set<int> s;
  51. insert(s,
  52. views::ints|views::take(10)|views::for_each([](int i){return yield_if(i%2==0,i);}));
  53. ::check_equal(s, {0,2,4,6,8});
  54. auto j = insert(s, 10);
  55. CHECK(j.first == prev(s.end()));
  56. CHECK(j.second == true);
  57. ::check_equal(s, {0,2,4,6,8,10});
  58. insert(views::ref(s), 12);
  59. ::check_equal(s, {0,2,4,6,8,10,12});
  60. }
  61. {
  62. const std::size_t N = 1024;
  63. vector_like<int> vl;
  64. insert(vl, vl.end(), views::iota(0, int{N}));
  65. CHECK(vl.reservation_count == 1u);
  66. CHECK(vl.last_reservation == N);
  67. auto r = views::iota(0, int{2 * N});
  68. insert(vl, vl.begin() + 42, begin(r), end(r));
  69. CHECK(vl.reservation_count == 2u);
  70. CHECK(vl.last_reservation == 3 * N);
  71. int i = 42;
  72. insert(vl, vl.end(), &i, &i + 1);
  73. CHECK(vl.reservation_count == 3u);
  74. CHECK(vl.last_reservation > 3 * N + 1);
  75. }
  76. return ::test_result();
  77. }