Conteúdo do Curso
C++ Data Types
C++ Data Types
Strings in Memory
As shown in the video, strings have length and capacity.
They can be accessed using .length()
and .capacity()
methods.
main
#include <iostream> int main() { std::string str = "String of 23 characters"; std::cout << "String: " << str << std::endl;; std::cout << "Length:" << str.length() << " Capacity:" << str.capacity() << std::endl; str.append("...Now 32"); std::cout << "---\nString: " << str << std::endl;; std::cout << "Length:" << str.length() << " Capacity:" << str.capacity() << std::endl;; }
There are also two methods to work with capacity, .reserve(n)
and shrink_to_fit()
.
.reserve(n)
– set capacity to at leastn
;.shrink_to_fit()
– set capacity the same as the length.
So the .shrink_to_fit()
is useful when you know you will not extend your string, but the capacity is greater than the length. And you can use .reserve(n)
if your string is likely to be appended multiple times.
main
#include <iostream> int main() { std::string str = "String of 23 characters"; std::cout << "Before reserve:\nLength:" << str.length() << " Capacity:" << str.capacity() << std::endl; str.reserve(60); std::cout << "After reserve:\nLength:" << str.length() << " Capacity:" << str.capacity() << std::endl; str.shrink_to_fit(); std::cout << "After shrink:\nLength:" << str.length() << " Capacity:" << str.capacity() << std::endl; }
Obrigado pelo seu feedback!