test_special_set_ops.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* Boost.MultiIndex test for special set operations.
  2. *
  3. * Copyright 2003-2015 Joaquin M Lopez Munoz.
  4. * Distributed under the Boost Software License, Version 1.0.
  5. * (See accompanying file LICENSE_1_0.txt or copy at
  6. * http://www.boost.org/LICENSE_1_0.txt)
  7. *
  8. * See http://www.boost.org/libs/multi_index for library home page.
  9. */
  10. #include "test_special_set_ops.hpp"
  11. #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
  12. #include <algorithm>
  13. #include <sstream>
  14. #include "pre_multi_index.hpp"
  15. #include "employee.hpp"
  16. #include <boost/detail/lightweight_test.hpp>
  17. using namespace boost::multi_index;
  18. static int string_to_int(const std::string& str)
  19. {
  20. std::istringstream iss(str);
  21. int res;
  22. iss>>res;
  23. return res;
  24. }
  25. struct comp_int_string
  26. {
  27. bool operator()(int x,const std::string& y)const
  28. {
  29. return x<string_to_int(y);
  30. }
  31. bool operator()(const std::string& x,int y)const
  32. {
  33. return string_to_int(x)<y;
  34. }
  35. };
  36. struct hash_string_as_int
  37. {
  38. int operator()(const std::string& x)const
  39. {
  40. return static_cast<int>(boost::hash<int>()(string_to_int(x)));
  41. }
  42. };
  43. struct eq_string_int
  44. {
  45. bool operator()(int x,const std::string& y)const
  46. {
  47. return x==string_to_int(y);
  48. }
  49. bool operator()(const std::string& x,int y)const
  50. {
  51. return operator()(y,x);
  52. }
  53. };
  54. void test_special_set_ops()
  55. {
  56. employee_set es;
  57. es.insert(employee(0,"Joe",31,1123));
  58. es.insert(employee(1,"Robert",27,5601));
  59. es.insert(employee(2,"John",40,7889));
  60. es.insert(employee(3,"Albert",20,9012));
  61. es.insert(employee(4,"John",57,1002));
  62. std::pair<employee_set_by_ssn::iterator,employee_set_by_ssn::iterator> p=
  63. get<ssn>(es).equal_range(
  64. "7889",hash_string_as_int(),eq_string_int());
  65. BOOST_TEST(std::distance(p.first,p.second)==1&&(p.first)->id==2);
  66. BOOST_TEST(
  67. get<ssn>(es).count(
  68. "5601",hash_string_as_int(),eq_string_int())==1);
  69. BOOST_TEST(
  70. get<ssn>(es).find(
  71. "1123",hash_string_as_int(),eq_string_int())->name=="Joe");
  72. BOOST_TEST(
  73. std::distance(
  74. get<age>(es).lower_bound("27",comp_int_string()),
  75. get<age>(es).upper_bound("40",comp_int_string()))==3);
  76. BOOST_TEST(es.count(2,employee::comp_id())==1);
  77. BOOST_TEST(es.count(5,employee::comp_id())==0);
  78. }