std:🧵:push_back() in C++ (original) (raw)

Last Updated : 22 Oct, 2024

The **std:🧵: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 ****** header file. In this article, we will learn about std:🧵:push_back() method in C++.

**Example:

C++ `

// C++ Program to illustrate how to use // std:🧵:push_back() method #include <bits/stdc++.h> using namespace std;

int main() { string s = "Geek";

// Appending character to the string
s.push_back('s');

cout << s;
return 0;

}

`

string::push_back() Syntax

s.**push_back(c);

where s the name of the string.

Parameters

Return Value

**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.

Complexity Analysis

The std::string container is generally implemented using dynamic arrays. So, std:🧵: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)

More Examples of string::push_back()

The following examples illustrate the use of string::push_back() method is different cases.

Example 1: Constructing Whole String using string::push_back()

C++ `

// C++ program to construct whole string using // string::push_back() method #include <bits/stdc++.h> using namespace std;

int main() { string s;

// Constructing string character by character
s.push_back('H');
s.push_back('e');
s.push_back('l');
s.push_back('l');
s.push_back('o');

cout << s;
return 0;

}

`

Example 2: Creating a Pattern using string::push_back() in Loop

C++ `

#include #include using namespace std;

int main() { string s = "*";

// Append '-' and '*' alternatively
for (int i = 0; i < 5; ++i) {
    s.push_back('-');
    s.push_back('*');
}

cout << s << endl;
return 0;

}

`