![]() |
VOOZH | about |
The std::string::push_back() method in C++ is used to append a single character at the end of string. It is the member function of std::string class defined inside <string> header file. In this article, we will learn about std::string::push_back() method in C++.
Example:
Geeks
s.push_back(c);
where s the name of the string.
Note: This function only works for C++ Style strings i.e. instances of std::string class and doesn't work for C-Style strings i.e. array of characters.
The std::string container is generally implemented using dynamic arrays. So, std::string::push_back() function basically adds a character to the end of the internal dynamic array.
Now, with dynamic arrays, if they have enough space, then the insertion at the end is fast O(1), but if they don't have enough space, then a reallocation might be needed, and it may take O(n) time. But the algorithm used for reallocation adjust the overall complexity to bring it to the amortized constant.
Time Complexity: O(1), Amortized Constant
Auxiliary Space: O(1)
The following examples illustrate the use of string::push_back() method is different cases.
Hello
*-*-*-*-*-*