std::string size() method
- since C++20
- since C++11
- until C++11
// Const version only
constexpr size_type size() const noexcept;
// Const version only
constexpr size_type length() const noexcept;
// Const version only
size_type size() const noexcept;
// Const version only
size_type length() const noexcept;
// Const version only
size_type size() const;
// Const version only
size_type length() const;
Returns the number of elements (CharT
s) in the container, i.e. std::distance(begin(), end())
.
Parametersβ
(none)
Return valueβ
The number of elements (CharT
s) in the container.
Complexityβ
- since C++11
- until C++11
Constant - O(1).
Unspecified.
Notesβ
For std::string
, the elements are bytes (objects of type char
), which are not the same as characters if a multibyte encoding such as UTF-8 is used.
Exampleβ
Main.cpp
#include <cassert>
#include <iterator>
#include <string>
int main()
{
std::string s("Exemplar");
assert(8 == s.size());
assert(s.size() == s.length());
assert(s.size() == static_cast<std::string::size_type>(
std::distance(s.begin(), s.end())));
std::u32string a(U"γγγΌγ»γ―γΌγ«γ"); // 8 code points
assert(8 == a.size()); // 8 code units in UTF-32
std::u16string b(u"γγγΌγ»γ―γΌγ«γ"); // 8 code points
assert(8 == b.size()); // 8 code units in UTF-16
std::string c("γγγΌγ»γ―γΌγ«γ"); // 8 code points
assert(24 == c.size()); // 24 code units in UTF-8
#if __cplusplus >= 202002
std::u8string d(u8"γγγΌγ»γ―γΌγ«γ"); // 8 code points
assert(24 == d.size()); // 24 code units in UTF-8
#endif
}
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.
Hover to see the original license.