vector_io.hpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* boost random/vector_io.hpp header file
  2. *
  3. * Copyright Steven Watanabe 2011
  4. * Distributed under the Boost Software License, Version 1.0. (See
  5. * 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 for most recent version including documentation.
  9. *
  10. * $Id$
  11. */
  12. #ifndef BOOST_RANDOM_DETAIL_VECTOR_IO_HPP
  13. #define BOOST_RANDOM_DETAIL_VECTOR_IO_HPP
  14. #include <vector>
  15. #include <iosfwd>
  16. #include <istream>
  17. #include <boost/io/ios_state.hpp>
  18. namespace boost {
  19. namespace random {
  20. namespace detail {
  21. template<class CharT, class Traits, class T>
  22. void print_vector(std::basic_ostream<CharT, Traits>& os,
  23. const std::vector<T>& vec)
  24. {
  25. typename std::vector<T>::const_iterator
  26. iter = vec.begin(),
  27. end = vec.end();
  28. os << os.widen('[');
  29. if(iter != end) {
  30. os << *iter;
  31. ++iter;
  32. for(; iter != end; ++iter)
  33. {
  34. os << os.widen(' ') << *iter;
  35. }
  36. }
  37. os << os.widen(']');
  38. }
  39. template<class CharT, class Traits, class T>
  40. void read_vector(std::basic_istream<CharT, Traits>& is, std::vector<T>& vec)
  41. {
  42. CharT ch;
  43. if(!(is >> ch)) {
  44. return;
  45. }
  46. if(ch != is.widen('[')) {
  47. is.putback(ch);
  48. is.setstate(std::ios_base::failbit);
  49. return;
  50. }
  51. boost::io::basic_ios_exception_saver<CharT, Traits> e(is, std::ios_base::goodbit);
  52. T val;
  53. while(is >> std::ws >> val) {
  54. vec.push_back(val);
  55. }
  56. if(is.fail()) {
  57. is.clear();
  58. e.restore();
  59. if(!(is >> ch)) {
  60. return;
  61. }
  62. if(ch != is.widen(']')) {
  63. is.putback(ch);
  64. is.setstate(std::ios_base::failbit);
  65. }
  66. }
  67. }
  68. }
  69. }
  70. }
  71. #endif // BOOST_RANDOM_DETAIL_VECTOR_IO_HPP