Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Strings in Memory | Text Data Type
C++ Data Types
course content

Зміст курсу

C++ Data Types

C++ Data Types

1. Introduction
2. Numerical Data Types
3. Text Data Type
4. Other Data Types and Concepts

Strings in Memory

As shown in the video, strings have length and capacity. They can be accessed using .length() and .capacity() methods.

cpp

main

12345678910111213
#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 least n;
  • .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.

cpp

main

12345678910111213
#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; }

Все було зрозуміло?

Секція 3. Розділ 7
We're sorry to hear that something went wrong. What happened?
some-alt