Convert Vector of Characters to String in C++
In this article, we will learn different methods to convert the vector of character to string in C++.
The most efficient method to convert the vector of characters to string is by using string's range constructor. Let’s take a look at an example:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> v = {'a', 'b', 'c', 'd', 'e'};
// Convert vector of char to string
string s(v.begin(), v.end());
cout << s;
return 0;
}
Output
abcde
Explanation: In the above code, we directly initialized the string s with the characters of the vector using its range constructor.
There are also some other methods in C++ by which we can convert the vector of character into string. Some of them are as follows:
Table of Content
Using accumulate()
The accumulate() method can also be used to convert the vector of character to string by iterating through every character and append it to resulting string.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> v = {'a', 'b', 'c', 'd', 'e'};
// Convert vector of character to string
string s = accumulate(v.begin(), v.end(), string(),
[](const string &a, char b) {
return a + b; });
cout << s;
return 0;
}
Output
abcde
Using Stringstream
Create a stringstream and insert all characters from the vector into it. After all characters are added, the stringstream str() function is called to convert the contents of the stream into a single string.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> v = {'a', 'b', 'c', 'd', 'e'};
// creating stringstream object
stringstream ss;
// Insert every character of vector into stream
for (auto it = v.begin(); it != v.end(); it++)
ss << *it;
// converts stream contents into a string
cout << ss.str() << endl;
return 0;
}
Output
abcde
Using push_back()
Iterate through the vector and add every character of vector into resultant string one by one using string push_back().
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> v = {'a', 'b', 'c', 'd', 'e'};
string s;
// Convert vector of character to string
for (auto i : v)
s.push_back(i);
cout << s;
return 0;
}
Output
abcde
In this method, we can replace the string push_back() method with string append() or even string insert() method.