Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to transform Vector into String?

  • Difficulty Level : Medium
  • 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.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

// C++ program transform a vector into
// a string.
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>
int main()
  std::vector<int> vec;
  std::ostringstream vts;
  if (!vec.empty())
    // Convert all but the last element to avoid a trailing ","
    std::copy(vec.begin(), vec.end()-1,
        std::ostream_iterator<int>(vts, ", "));
    // Now add the last element with no delimiter
    vts << vec.back();
  std::cout << vts.str() << std::endl;


1, 2, 3, 4, 5, 6

This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :