Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

I also tried std::span:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading