std::string in C++ Without Changing Its CapacityWhen 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.
size() and capacity()?size(): The number of characters currently in the string.
capacity(): The total memory allocated to the string (always ≥ size()).
For example:
cpp
Copy
std::string str = "Hello";  
std::cout << str.size();      // Output: 5  
std::cout << str.capacity();  // Output: 15 (varies by compiler)  
The resize() method changes the size() of the string. However:
If you increase the size beyond the current capacity(), the string reallocates memory, increasing capacity.
If you decrease the size, the capacity() usually stays the same (no memory is freed by default).
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)  
To avoid changing the capacity, ensure the new size() does not exceed the current capacity():
cpp
Copy
size_t current_cap = str.capacity();  
cpp
Copy
str.resize(new_size);  // Only works if new_size ≤ current_cap  
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;  
}