Skip to main content

std::string clear() method

// Non const version only
constexpr void clear() noexcept;

Removes all characters from the string as if by executing

erase(begin(), end())
Invalidation

All pointers, references, and iterators are invalidated.

Parameters

(none)

Return value

(none)

Complexity

The standard guarantees at least linear in the size of the container - O(size()).
But existing implementations operate in constant time - O(1).

Notes

Unlike for std::vector::clear(), the C++ standard does not explicitly require that capacity is unchanged by this function, but existing implementations do not change capacity.
This means that they do not release the allocated memory (see also shrink_to_fit()).

Example

#include <cassert>
#include <string>

int main()
{
std::string s{ "Exemplar" };
std::string::size_type const capacity = s.capacity();

s.clear();
assert(s.capacity() == capacity); // <- not guaranteed
assert(s.empty());
assert(s.size() == 0);
}
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::string clear() method

// Non const version only
constexpr void clear() noexcept;

Removes all characters from the string as if by executing

erase(begin(), end())
Invalidation

All pointers, references, and iterators are invalidated.

Parameters

(none)

Return value

(none)

Complexity

The standard guarantees at least linear in the size of the container - O(size()).
But existing implementations operate in constant time - O(1).

Notes

Unlike for std::vector::clear(), the C++ standard does not explicitly require that capacity is unchanged by this function, but existing implementations do not change capacity.
This means that they do not release the allocated memory (see also shrink_to_fit()).

Example

#include <cassert>
#include <string>

int main()
{
std::string s{ "Exemplar" };
std::string::size_type const capacity = s.capacity();

s.clear();
assert(s.capacity() == capacity); // <- not guaranteed
assert(s.empty());
assert(s.size() == 0);
}
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.