c++ - 有没有办法从 string_view 创建字符串流而不复制数据?

标签 c++ c++17 stringstream

我认为这是一个非常简单的问题。我特别想使用 std::get_time ,但它需要某种类型的流来使用。我正在 string_view 中传递数据,并且希望避免仅仅为了解析日期而复制它。

最佳答案

您可以使用 Boost.Iostreams 库轻松做到这一点:

#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++ 标准未能满足其要求:

The effect [of setbuf] is implementation-defined: some implementations do nothing, while some implementations clear the std::string member currently used as the buffer and begin using the user-supplied character array of size n, whose first element is pointed to by s, as the buffer and the input/output character sequence.

关于c++ - 有没有办法从 string_view 创建字符串流而不复制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524805/

相关文章:

c++ - 让 CImg 在 XCode 中工作

c++ - 你能捕获递归 lambda 中的引用吗?

c++ - 如何根据模板变量参数多次扩展语句

c++ - 为 fwprintf 写一个包装器

c++ - 从字符串中提取字符时,基于范围的循环和stringstream有什么区别

c++ - 如何在 GTK Stack Switcher 中使用图像

c++ - 函数参数包

c++ - 在STL关联容器中使用基于迭代器的搜索和使用是否更快?

c++ - 别名 boost::variant 或 std::variant 不可编译

c++ - Stringstream C++ while 循环