Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a vector<int> into a string? [duplicate]

Tags:

c++

stl

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?

like image 331
Legend Avatar asked Sep 04 '25 17:09

Legend


2 Answers

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()

like image 195
fbrereto Avatar answered Sep 07 '25 11:09

fbrereto


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'

like image 45
John Dibling Avatar answered Sep 07 '25 12:09

John Dibling