doc_custom_vector.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost
  4. // Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/container for documentation.
  8. //
  9. //////////////////////////////////////////////////////////////////////////////
  10. //[doc_custom_vector
  11. #include <boost/container/vector.hpp>
  12. #include <boost/static_assert.hpp>
  13. //Make sure assertions are active
  14. #ifdef NDEBUG
  15. #undef NDEBUG
  16. #endif
  17. #include <cassert>
  18. int main ()
  19. {
  20. using namespace boost::container;
  21. //This option specifies that a vector that will use "unsigned char" as
  22. //the type to store capacity or size internally.
  23. typedef vector_options< stored_size<unsigned char> >::type size_option_t;
  24. //Size-optimized vector is smaller than the default one.
  25. typedef vector<int, new_allocator<int>, size_option_t > size_optimized_vector_t;
  26. BOOST_STATIC_ASSERT(( sizeof(size_optimized_vector_t) < sizeof(vector<int>) ));
  27. //Requesting capacity for more elements than representable by "unsigned char"
  28. //is an error in the size optimized vector.
  29. bool exception_thrown = false;
  30. try { size_optimized_vector_t v(256); }
  31. catch(...){ exception_thrown = true; }
  32. assert(exception_thrown == true);
  33. //This option specifies that a vector will increase its capacity 50%
  34. //each time the previous capacity was exhausted.
  35. typedef vector_options< growth_factor<growth_factor_50> >::type growth_50_option_t;
  36. //Fill the vector until full capacity is reached
  37. vector<int, new_allocator<int>, growth_50_option_t > growth_50_vector(5, 0);
  38. const std::size_t old_cap = growth_50_vector.capacity();
  39. growth_50_vector.resize(old_cap);
  40. //Now insert an additional item and check the new buffer is 50% bigger
  41. growth_50_vector.push_back(1);
  42. assert(growth_50_vector.capacity() == old_cap*3/2);
  43. return 0;
  44. }
  45. //]