Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ what is CharT element in string::size?

Tags:

c++

stdstring

From http://en.cppreference.com/w/cpp/string/basic_string/size

The number of CharT elements in the string.

What is CharT element?

like image 205
Rick Avatar asked Jun 04 '18 12:06

Rick


People also ask

What is the size of std::string?

While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation. To achieve this libc++ uses a neat trick: the size of the string is not saved as-is but rather in a special way: if the string is short (< 23 bytes) then it stores size() * 2 .

Does std::string store size?

std::string actually maintains the size as one of its data member.

What is the difference between size () and length () in C++?

The size() function is consistent with other STL containers (like vector, map, etc.) and length() is consistent with most peoples intuitive notion of character strings like a word, sentence or paragraph. We say a paragraph'ss length not its size, so length() is to make things more readable.

What is the size of a string in C++?

In C++, string length really represents the number of bytes used to encode the given string. Since one byte in C++ usually maps to one character, this metric mostly means “number of characters,” too.


1 Answers

std::basic_string is a class template that is defined as

template< 
    class CharT, 
    class Traits = std::char_traits<CharT>, 
    class Allocator = std::allocator<CharT>
> class basic_string;

where CharT is the type of character stored by the string. So std::basic_string::size returns the number of CharT elements in the string.

like image 62
NathanOliver Avatar answered Sep 30 '22 01:09

NathanOliver