The question is simple: What is the quickest way of finding the position of the null-terminator ('\0') in a string buffer?
std::array<char, 100> str { "A sample string literal" };
I guess one option is to use the std::strlen
.
Another option that I can think of is std::find
or maybe even std::ranges::find
:
const auto posOfNull { std::find( str.cbegin( ), str.cend( ), '\0' ) };
Now would it make a difference if an ExecutionPolicy
(e.g. std::execution::par
) was passed to it as its first argument? If it would, then which policy is the appropriate one for this particular case?
Or maybe a 3rd option that I don't know about?
CodePudding user response:
What is the quickest way of finding the position of the null-terminator ('\0') in a string buffer?
I'm going to assume that you mean "to find the first null terminator".
Fastest depends on details. You have to measure to find out. std::strlen
is a fairly safe default choice.
Now would it make a difference if an ExecutionPolicy (e.g. std::execution::par
The length of your buffer is 100. The overhead from multi threading may easily exceed the the time to find the terminator in a single thread.
If it would, then which policy is the appropriate one for this particular case?
The one that you have measured to be the fastest. None of them would break the correctness of the loop.
Or maybe a 3rd option that I don't know about?
You can use std::char_traits::length
. Its benefits over std::strlen
are that it works with all character types (compared to only char
), and it is constexpr
which allows using it in constant expressions.