Convert vector to string in C++

Given a vector, we are supposed to make a string containing all of its elements in C++. It will be a single string of vector elements.

Example:

Vector Elements: {“hello”, “what”, “is”, “your”, “name”}

Output String: hellowhatisyourname

First Approach (Using + operator):

Here we have to concatenate given array elements to a string so we can simply use the “+” operator to concatenate all the strings. The steps involved are-

  1. First, take an empty output string.
  2. Now traverse through the vector.
  3. Keep adding elements of the vector to the output string while traversing.

Below is the code implementation to understand it better.

#include<bits/stdc++.h>
using namespace std;

int main(){
    // Given Vector
    vector<string>arr={"hello","what","is","your","name"};
    // Output string
    string out="";
    
    // Add elements of the vector using + operator 
    for(auto& it:arr){
        out+=it;
    }
    // output the final string
    cout<<out<<endl;
    return 0;
}

Time Complexity: O(n) where n is the sum of all characters of the given vector.

Space Complexity: O(1) since no extra space is used.

 

Second Approach (using push_back):

We can also apply the above idea using push_back in the string. But here this should be noted that push_back() doesn’t allow adding a complete string to the given string. It can only add a character to the back of the string. So we have to traverse through each string of the given vector separately.

Below is the code implementation to understand it better.

#include<bits/stdc++.h>
using namespace std;

int main(){
    vector<string>arr={"hello","what","is","your","name"};
    string out="";
    
    for(auto& it:arr){
        for(auto & i:it){
            out.push_back(i);
        }
    }
    cout<<out<<endl;
    return 0;
}

Time Complexity: O(n^2) where n is the sum of all characters of the vector element. Because push_back takes O(n) time to add an element to the back of the string so for every character it will take the extra O(n) time. Hence complexity is O(n^2).

Space Complexity: O(1) since no extra space is used.

Leave a Reply

Your email address will not be published. Required fields are marked *