std::string_view empty() method
- od C++20
- od C++17
// Const version only
[[nodiscard]] constexpr bool empty() const noexcept;
// Const version only
constexpr bool empty() const noexcept;
Checks if the container has no elements, i.e. whether begin() == end()
.
Parameters
(none)
Return value
true
if the container is empty, false
otherwise.
Complexity
Constant - O(1).
Why [[nodiscard]]
?
The [[nodiscard]]
attribute is an attribute that invokes compiler warnings whenever
a function has been called and it's result has been discarded.
The reason behind the attribute being applied only to the empty
method is that
it's likely that the programmer might confuse the adjective empty
(which would mean - is this container empty?)
for the verb empty
(which would mean - please empty this container for me.).
Example
#include <string_view>
#include <iostream>
void check_string(std::string_view ref)
{
// Print a string surrounded by single quotes, its length
// and whether it is considered empty.
std::cout << std::boolalpha
<< "'" << ref << "' has " << ref.size()
<< " character(s); emptiness: " << ref.empty() << '\n';
}
int main(int argc, char **argv)
{
// An empty string
check_string("");
// Almost always not empty: argv[0]
if (argc > 0)
check_string(argv[0]);
}
'' has 0 character(s); emptiness: true
'./a.out' has 7 character(s); emptiness: false
Hover to see the original license.