Short answer: use resize (10) instead of reserve (10)
Long answer: When implementing std :: string, there are two sizes and capacity of variables. Capacity is the amount of memory that you allocated for the row. Size - how many valid elements (in your case, char) are allowed in your string. Please note: capacity will always be less than or equal to size. When you call reserve (), you change capacity. When you resize (), you can not only resize, but also change the capacity if the size> capacity, in which this formula will be applied:
if (size > capacity){ capacity = max(size, capacity*2); //Why multiply capacity by 2 here? This is to achieve amortized O(1) while resizing }
Here is a code example of what the OP wants, and another code to better explain the size and capacity
#include <iostream>
Result:
length of s2 before reserve: 5 capacity of s2 before reserve: 5 length of s2 after reserve: 5 capacity of s2 after reserve: 10 length of s2 after resize: 8 capacity of s2 after resize: 10 [hello] [hello.o] length of s2 after appending: 11 capacity of s2 after appending: 20 After appending: [hello] [hello.ohii]
source share