79511962

Date: 2025-03-16 00:28:57
Score: 0.5
Natty:
Report link

How to Resize a std::string in C++ Without Changing Its Capacity

When working with std::string in C++, resizing it is straightforward, but ensuring its capacity (the allocated memory size) stays the same can be confusing. Let’s break down how to resize a string while preserving its capacity—no jargon, just clarity.


What Are size() and capacity()?

For example:

cpp

Copy

std::string str = "Hello";  
std::cout << str.size();      // Output: 5  
std::cout << str.capacity();  // Output: 15 (varies by compiler)  

How Resizing Affects Capacity

The resize() method changes the size() of the string. However:

  1. If you increase the size beyond the current capacity(), the string reallocates memory, increasing capacity.

  2. If you decrease the size, the capacity() usually stays the same (no memory is freed by default).

Example:

cpp

Copy

std::string str = "Hello";  
str.reserve(20);  // Force capacity to 20  
str.resize(10);   // Size becomes 10, capacity remains 20  
str.resize(25);   // Size 25, capacity increases (now ≥25)  

How to Resize a String and Keep the Same Capacity

To avoid changing the capacity, ensure the new size() does not exceed the current capacity():

Step 1: Check the current capacity.

cpp

Copy

size_t current_cap = str.capacity();  

Step 2: Resize within the current capacity.

cpp

Copy

str.resize(new_size);  // Only works if new_size ≤ current_cap  

Full Example:

cpp

Copy

#include <iostream>  
#include <string>  

int main() {  
    std::string str = "C++ is fun!";  
    str.reserve(50);  // Set capacity to 50  

    std::cout << "Original capacity: " << str.capacity() << "\n"; // 50  

    // Resize to 20 (within capacity)  
    str.resize(20);  
    std::cout << "New size: " << str.size() << "\n";      // 20  
    std::cout << "Capacity remains: " << str.capacity();  // 50  

    return 0;  
}  

Read More...

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): How to
  • Low reputation (1):
Posted by: dooo. xxturtu