How to transform Vector into String?
Last Updated :
06 Jul, 2017
Vectors: Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. C++ program to transform vector into string.
String: C++ has in its definition a way to represent sequence of characters as an object of class. This class is called std:: string.
std::ostringstream: It is an Output stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str.
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>
int main()
{
std::vector< int > vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
vec.push_back(6);
std::ostringstream vts;
if (!vec.empty())
{
std::copy(vec.begin(), vec.end()-1,
std::ostream_iterator< int >(vts, ", " ));
vts << vec.back();
}
std::cout << vts.str() << std::endl;
}
|
Output:
1, 2, 3, 4, 5, 6
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...