Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a vector<int> to a string

I have a vector<int> container that has integers (e.g. {1,2,3,4}) and I would like to convert to a string of the form

"1,2,3,4" 

What is the cleanest way to do that in C++? In Python this is how I would do it:

>>> array = [1,2,3,4] >>> ",".join(map(str,array)) '1,2,3,4' 
like image 792
D R Avatar asked Sep 16 '09 03:09

D R


People also ask

How do I convert an int to a string in CPP?

The next method in this list to convert int to string in C++ is by using the to_string() function. This function is used to convert not only the integer but numerical values of any data type into a string. The to_string() method is included in the header file of the class string, i.e., <string> or <cstring>.

Can a string be a vector?

From a purely philosophical point of view: yes, a string is a type of vector. It is a contiguous memory block that stores characters (a vector is a contiguous memory block that stores objects of arbitrary types). So, from this perspective, a string is a special kind of vector.


2 Answers

Definitely not as elegant as Python, but nothing quite is as elegant as Python in C++.

You could use a stringstream ...

#include <sstream> //...  std::stringstream ss; for(size_t i = 0; i < v.size(); ++i) {   if(i != 0)     ss << ",";   ss << v[i]; } std::string s = ss.str(); 

You could also make use of std::for_each instead.

like image 95
Brian R. Bondy Avatar answered Oct 09 '22 01:10

Brian R. Bondy


Using std::for_each and lambda you can do something interesting.

#include <iostream> #include <sstream>  int main() {      int  array[] = {1,2,3,4};      std::for_each(std::begin(array), std::end(array),                    [&std::cout, sep=' '](int x) mutable {                        out << sep << x; sep=',';                    }); } 

See this question for a little class I wrote. This will not print the trailing comma. Also if we assume that C++14 will continue to give us range based equivalents of algorithms like this:

namespace std {    // I am assuming something like this in the C++14 standard    // I have no idea if this is correct but it should be trivial to write if it  does not appear.    template<typename C, typename I>    void copy(C const& container, I outputIter) {copy(begin(container), end(container), outputIter);} } using POI = PrefexOutputIterator;    int main() {      int  array[] = {1,2,3,4};      std::copy(array, POI(std::cout, ","));   // ",".join(map(str,array))               // closer } 
like image 24
Martin York Avatar answered Oct 08 '22 23:10

Martin York