How to transform a vector<int> into a string? [duplicate]
I am trying to pass a value from C++ t开发者_JAVA技巧o TCL. As I cannot pass pointers without the use of some complicated modules, I was thinking of converting a vector to a char array and then passing this as a null terminated string (which is relatively easy).
I have a vector as follows:
12, 32, 42, 84
which I want to convert into something like:
"12 32 42 48"
The approach I am thinking of is to use an iterator to iterate through the vector and then convert each integer into its string representation and then add it into a char array (which is dynamically created initially by passing the size of the vector). Is this the right way or is there a function that already does this?
What about:
std::stringstream result;
std::copy(my_vector.begin(), my_vector.end(), std::ostream_iterator<int>(result, " "));
Then you can pass the pointer from result.str().c_str()
You can use copy
in conjunction with a stringstream
object and the ostream_iterator
adaptor:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v;
v.push_back(12);
v.push_back(32);
v.push_back(42);
v.push_back(84);
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
cout << "'" << s << "'";
return 0;
}
Output is:
'12 32 42 84'
I'd use a stringstream to build the string. Something like:
std::vector<int>::const_iterator it;
std::stringstream s;
for( it = vec.begin(); it != vec.end(); ++it )
{
if( it != vec.begin() )
s << " ";
s << *it;
}
// Now use s.str().c_str() to get the null-terminated char pointer.
You got it right, but you can use std::ostringstream
to create your char array.
#include <sstream>
std::ostringstream StringRepresentation;
for ( vector<int>::iterator it = MyVector.begin(); it != MyVector.end(); it++ ) {
StringRepresentation << *it << " ";
}
const char * CharArray = StringRepresentation.str().c_str();
In this case, CharArray
is only for reading. If you want to modify the values, you will have to copy it. You can simplify this by using Boost.Foreach.
精彩评论