Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++11 何时使用ostream_迭代器_C++11_Iterator_Ostream - Fatal编程技术网

C++11 何时使用ostream_迭代器

C++11 何时使用ostream_迭代器,c++11,iterator,ostream,C++11,Iterator,Ostream,据我所知,我们可以在c++11中使用ostream\u迭代器来打印容器。 例如, std::vector<int> myvector; for (int i=1; i<10; ++i) myvector.push_back(i*10); std::copy ( myvector.begin(), myvector.end(), std::ostream_iterator<int>{std::cout, " "} ); std::vector myvector;

据我所知,我们可以在c++11中使用
ostream\u迭代器
来打印容器。
例如,

std::vector<int> myvector;
for (int i=1; i<10; ++i) myvector.push_back(i*10);

std::copy ( myvector.begin(), myvector.end(), std::ostream_iterator<int>{std::cout, " "} );
std::vector myvector;
for(int i=1;i是一个单通输出迭代器,因此它可以用于任何接受这种迭代器的算法中。使用它输出int-s的向量只是为了展示它的功能

在我看来,传统的方式更快,因为没有拷贝,对吗


您可能会在这里发现:该副本的实现方式与for auto循环非常相似。它还专门用于各种类型,以尽可能高效地工作。另一方面,写入std::ostream_迭代器是通过分配给它来完成的,您可以在这里读到:它解析为
*out_stream。不同之处在于多态性与hardco无数据流。
std::ostream\u迭代器
从继承自
std::ostream
的任何类构建自身,因此在运行时,您可以根据函数运行的上下文更改或连接迭代器以写入不同的输出流类型

第二个代码段使用了一个硬编码的
std::cout
,它在运行时无法更改

for(const auto & i : myvector) std::cout<<i<<" ";
struct MyData {
    std::vector<int> data = {1,2,3,4};

    template<typename T>
    void serialize(T iterator) {
        std::copy(data.begin(), data.end(), iterator);
    }
};

int main()
{
    MyData data;

    // Output to stream 
    data.serialize(std::ostream_iterator<int>(std::cout, ","));

    // Output to memory
    std::vector<int> copy;
    data.serialize(std::back_inserter(copy));

    // Other uses with different iterator adaptors:
    // std::front_insert_iterator
    // other, maybe custom ones
}