std::string size() 方法
- 自 C++20 起
- 自 C++11 起
- 直到 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;
返回容器中元素的数量(CharT
s),即 std::distance(begin(), end())
。
参数
(无)
返回值
容器中元素的数量(CharT
s)。
复杂度
- 自 C++11 起
- 直到 C++11
常量 - O(1)。
未指定。
备注
对于 std::string
,元素是字节(char
类型的对象),如果使用多字节编码(如 UTF-8),则与字符不同。
示例
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
}