I am trying to pass a value from C++ to 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'
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