简体   繁体   English

在不复制的情况下,如何在 C++ 中打印部分 std::string?

[英]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.

相关问题 如何在不复制和保留std :: string对象的情况下获取C ++ std :: string char数据的所有权? - How can I take ownership of a C++ std::string char data without copying and keeping std::string object? 如何在不复制的情况下将std :: string的一部分放入流缓冲中? - How to get part of a std::string into a streambuf without copying? 如何将整个文件读入 C++ 中的 std::string? - How do I read an entire file into a std::string in C++? 如何在 C++ 中获取 a 字符串的一部分? - How do I get a part of the a string in C++? C++ 如何替换字符串的一部分? - C++ How do I replace part of a string? 如何在C ++中的字符串中找到完整的单词(不是它的一部分) - How do I find a complete word (not part of it) in a string in C++ 如何在C ++中的字符串中显式打印“ \\ n” - How do I print “\n” explicitly in a string in c++ 我该如何遍历std :: map中的元素 <std::string,shared_ptr<A> &gt;在C ++中 - how to do i iterate through elements of in std::map<std::string,shared_ptr<A>> in c++ 如何在不使用`std :: setw`,`std :: left`和`std :: right`的情况下在C ++中打印此模式 - How to print this pattern in C++ without using `std::setw`, `std::left` and `std::right` 如何使用std :: string而不复制? - How to use a std::string without copying?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM