How to Convert Vector of int into String?
Last Updated :
03 Dec, 2024
In C++, there are numerous cases where a vector of integers is needs to be converted into a string. In this article, we will learn the different methods to convert the vector of int into string in C++.
The simplest method to convert the vector of int into string is by creating a stringstream and adding each integer to it one by one in the desired format. Let’s take a look at an example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
stringstream ss;
// Insert every element of vector into stream
for (int i : v)
ss << i;
// converts stream contents into a string
cout << ss.str();
return 0;
}
Explanation: In the above code, first we create a stringstream object and inserts each element of the vector v into the stream using a loop. After all elements are added to the stream, the stringstream str() function is called to convert the contents of the stream into a single string.
There are also some other methods in C++ to convert vector of int into string. Some of them are as follows:
Using accumulate()
The accumulate() method can be used to convert a vector of integers into a string by applying to_string() to each element and appending the result to a string variable s.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
// Convert vector of integer to string
string s = accumulate(v.begin(), v.end(), string(),
[](const string &a, int b) {
return a + to_string(b); });
cout << s << endl;
return 0;
}
The transform() method can also be used to convert the vector of integer to string by transforming every element to its character equivalent by adding with '0' and then appended them to resultant string using back_inserter().
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
string s;
// Convert vector of integer to string
transform(v.begin(), v.end(), back_inserter(s),
[](int i) { return i + '0'; });
cout << s;
return 0;
}
Manually using Loop
To convert a vector of integers into a string iterate through each element of the vector, convert it to a string using their ASCII values and add it to the end of the string.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
string s;
// Convert vector of int to string
for (auto i : v) {
char c = i + '0';
s += c;
}
cout << s;
return 0;
}