[英]Without copying, how do I print part of a std::string in C++?
Assume that I want to print the first word.假设我想打印第一个字。 The most obvious way would be like this:
最明显的方法是这样的:
string line = "Hello Hello";
const auto space_iter = find(line.cbegin(), line.cend(), ' ');
cout<<string(line.cbegin(), space_iter)<<endl;
But I'm printing profiling logs for my game at over 60fps, so such memory allocation and copying matters.但是我正在以超过 60fps 的速度为我的游戏打印分析日志,因此 memory 分配和复制很重要。
I also tried std::span
:我也试过
std::span
:
string line = "Hello Hello";
const auto space_iter = find(line.cbegin(), line.cend(), ' ');
cout<<span(line.cbegin(), space_iter)<<endl;
But it seems that std::cout
can't print a std::span
, and gcc gives me 500+ lines of errors.但似乎
std::cout
无法打印std::span
,并且 gcc 给了我 500 多行错误。
C++20 gives std::string_view
a convenient constructor that takes contiguous iterators. C++20 为
std::string_view
提供了一个方便的构造函数,它采用连续的迭代器。 Like those of std::string
.像
std::string
的那些。 Pre-C++20, getting a substring as a string_view
was a bit more complex, but now it's pretty trivial:在 C++20 之前,获取 substring 作为
string_view
有点复杂,但现在它非常简单:
cout << std::string_view(line.cbegin(), space_iter) << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.