码迷,mamicode.com
首页 > 其他好文 > 详细

std::ostream_iterator用法

时间:2015-01-16 16:27:35      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

 

Defined in header <iterator>
    template< class T, class CharT = char, class Traits = std::char_traits<CharT>>
          class ostream_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void>

std::ostream_iterator is a single-pass OutputIterator that writes successive objects of type T into thestd::basic_ostream object for which it was constructed, using operator<<. Optional delimiter string is written to the output stream after every write operation. The write operation is performed when the iterator (whether dereferenced or not) is assigned to. Incrementing the std::ostream_iterator is a no-op.

In a typical implementation, the only data members of std::ostream_iterator are a pointer to the associatedstd::basic_ostream and a pointer to the first character in the delimiter string.

When writing characters, std::ostreambuf_iterator is more efficient, since it avoids the overhead of constructing and destructing the sentry object once per character.

 

 1 #include <iostream>
 2 #include <sstream>
 3 #include <iterator>
 4 #include <numeric>
 5  
 6 int main()
 7 {
 8     std::istringstream str("0.1 0.2 0.3 0.4");
 9     std::partial_sum(std::istream_iterator<double>(str),
10                       std::istream_iterator<double>(),
11                       std::ostream_iterator<double>(std::cout, " "));
12 }

Output:

0.1 0.3 0.6 1
 1 // ostream_iterator example
 2 #include <iostream>     // std::cout
 3 #include <iterator>     // std::ostream_iterator
 4 #include <vector>       // std::vector
 5 #include <algorithm>    // std::copy
 6 
 7 int main () {
 8   std::vector<int> myvector;
 9   for (int i=1; i<10; ++i) myvector.push_back(i*10);
10 
11   std::ostream_iterator<int> out_it (std::cout,", ");
12   std::copy ( myvector.begin(), myvector.end(), out_it );
13   return 0;
14 }

Output:
   10, 20, 30, 40, 50, 60, 70, 80, 90,

 

std::ostream_iterator用法

标签:

原文地址:http://www.cnblogs.com/scw2901/p/4228909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!