user120920
user120920

Reputation: 89

What goes on when you concatenate a char to a string in C++?

For example, the following code reverses a string, but what actually goes on when I'm adding each character to a string? Is it efficient? Does it create a new char array every time, or does it double the size every time it fills up, or?:

#include <iostream>
#include <stack>
using namespace std;

int main()
{
    string test = "testing";

    stack<char> first;

    for(int i = 0; test[i]; i++)
    {
        first.push(test[i]);
    }
    string reversed;
    int i=0;
    while(!first.empty())
    {
        reversed += first.top();
        first.pop();
    }
    cout << test << reversed;
}

Upvotes: 1

Views: 98

Answers (2)

basav
basav

Reputation: 1495

When a string is added to another string, in the case of + operator, the resultant string is move constructed.

String a("hello"); a+="goodmorning";

A string uses a char buffer underneath, and the size is set to default value at construction time.You can alter it using reserve.But during concatenation, if the reserved size is exceeded, then the buffer has to be extended.

Upvotes: 1

Mohit Jain
Mohit Jain

Reputation: 30489

Yes the code is non-efficient. You should use std::reverse. But if you still want to stick with your approach, use std::string::reserve to increase the capacity of string.

string reversed;
reversed.capacity(test.size());

When you add character by character to std::vector and std::string, they resize when the capacity is exhausted by a constant factor. (typically 2, but may be different)

This exponential growth makes sure that cost of insertion is constant asymptotically.

Upvotes: 1

Related Questions