据我所知,我们可以在c++11中使用ostream_iterator
来打印容器。
例如,
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, " "} );
我不知道我们什么时候以及为什么使用上面的代码,而不是传统的方式,例如:
for(const auto & i : myvector) std::cout<<i<<" ";
在我看来,传统方式更快,因为没有复制
,我是对的吗?
最佳答案
std::ostream_iterator是一个单遍 OutputIterator,因此它可以用于任何接受此类迭代器的算法中。使用它来输出 int-s 向量只是为了展示它的功能。
In my opinion, the traditional way is faster because there is no copy, am I right?
您可以在这里找到:http://en.cppreference.com/w/cpp/algorithm/copy该副本的实现方式与 for-auto 循环非常相似。它还专门针对各种类型,以尽可能高效地工作。另一方面,写入 std::ostream_iterator 是通过对其进行赋值来完成的,您可以在此处阅读: http://en.cppreference.com/w/cpp/iterator/ostream_iterator/operator%3D它解析为 *out_stream << value;
操作(如果忽略分隔符)。
您可能还会发现该迭代器存在在末尾插入额外尾随定界符的问题。为了解决这个问题,(可能在 C++17 中)将有一个新的单遍 OutputIterator std::experimental::ostream_joiner
一个简短的(也许很愚蠢的)示例,其中使用迭代器很有用。关键是您可以将数据定向到任何接收器 - 文件、控制台输出、内存缓冲区。无论您选择什么输出,MyData::serialize
不需要修改,只需要提供OutputIterator即可。
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
}
关于c++11 - 何时使用 ostream_iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37688145/