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.
I also tried 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.
C++20 gives std::string_view
a convenient constructor that takes contiguous iterators. Like those of std::string
. Pre-C++20, getting a substring as a string_view
was a bit more complex, but now it's pretty trivial:
cout << std::string_view(line.cbegin(), space_iter) << endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.