有没有一种方法可以从string_view创建一个stringstream而不复制数据? [英] Is there a way to create a stringstream from a string_view without copying data?
问题描述
我认为这是一个非常简单的问题。我特别想使用 std :: get_time
,但是它需要使用某种流。我在 string_view
中传递数据,并希望避免为了分析日期而复制它。
I think that's a pretty straighforward question. I'd specifically like to use std::get_time
, but it requires some sort of a stream to be used with. I am passing the data in a string_view
and would like to avoid copying it just to parse the date.
推荐答案
您可以使用Boost.Iostreams库轻松做到这一点:
You can do that easily with Boost.Iostreams library:
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>
#include <string>
int main() {
std::string_view buf{"hello\n"};
boost::iostreams::stream<boost::iostreams::basic_array_source<char>> stream(buf.begin(), buf.size());
std::string s;
stream >> s;
std::cout << s << '\n';
}
您应该能够使用 std :: stringstream
和 std :: basic_stringbuf< CharT,Traits,Allocator> :: setbuf
,但C ++标准降低了其要求:
You should be able to do that with std::stringstream
and std::basic_stringbuf<CharT,Traits,Allocator>::setbuf
but the C++ standard botched its requirements:
[
setbuf
]的效果是实现定义的:某些实现不执行任何操作,而某些实现则清除std :: string
成员当前用作缓冲区,并开始使用用户提供的大小为n
的字符数组,其第一个元素为s
指向的缓冲区和输入/输出字符序列。
The effect [of
setbuf
] is implementation-defined: some implementations do nothing, while some implementations clear thestd::string
member currently used as the buffer and begin using the user-supplied character array of sizen
, whose first element is pointed to bys
, as the buffer and the input/output character sequence.
这篇关于有没有一种方法可以从string_view创建一个stringstream而不复制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!