Namespaces
Variants

std::ostreambuf_iterator<CharT,Traits>:: ostreambuf_iterator

From cppreference.net
Iterator library
Iterator concepts
Iterator primitives
Algorithm concepts and utilities
Indirect callable concepts
Common algorithm requirements
(C++20)
(C++20)
(C++20)
Utilities
(C++20)
Iterator adaptors
Range access
(C++11) (C++14)
(C++14) (C++14)
(C++11) (C++14)
(C++14) (C++14)
(C++17) (C++20)
(C++17)
(C++17)
(1)
ostreambuf_iterator ( streambuf_type * buffer ) throw ( ) ;
(C++11 前)
ostreambuf_iterator ( streambuf_type * buffer ) noexcept ;
(C++11 起)
(2)
ostreambuf_iterator ( ostream_type & stream ) throw ( ) ;
(C++11 前)
ostreambuf_iterator ( ostream_type & stream ) noexcept ;
(C++11 起)
1) 构造迭代器时,将私有成员 streambuf_type* 设置为 buffer ,并将 failed() 标志设置为 false 。若 buffer 为空指针,则行为未定义。
2) 等同于 ostreambuf_iterator ( stream. rdbuf ( ) )

参数

stream - 该迭代器将访问其 rdbuf() 的输出流
buffer - 该迭代器将访问的输出流缓冲区

示例

#include <fstream>
#include <iostream>
#include <iterator>
int main()
{
    const char* file = "test.txt";
    {
        std::basic_filebuf<char> f;
        f.open(file, std::ios::out);
        std::ostreambuf_iterator<char> out1(&f);
        *out1 = 'a'; // 通过迭代器写入文件
    }
    // 从文件读取内容
    char a;
    std::cout << ((std::ifstream{file} >> a), a) << std::endl;
    std::ostreambuf_iterator<wchar_t> out2{std::wcout};
    *out2 = L'b';
}

输出:

a
b

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 应用于 发布时行为 正确行为
LWG 112 C++98 要求“参数不能为 null”被应用于重载 (2) 改为应用于重载
(1)
P2325R3 C++20 提供了默认构造函数,因为 C++20
迭代器必须满足 default_initializable
随同该要求
一并移除