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'
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>.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With