Connecting Tech Pros Worldwide Forums | Help | Site Map

vector<int> to list of str

Member
 
Join Date: Oct 2009
Posts: 33
#1: Oct 8 '09
hello there,
i would like to convert a list of vector int into a list of string where i need to add some space between those char in that string.

what's on my mind is that to use sstream to convert each int into char and add space which definetely will be a few of if statement in my for loop

But i think it would make my code less efficient in terms of time.correct me if i'm wrong.is there any better way of doing it?

thanks.

myusernotyours's Avatar
Familiar Sight
 
Join Date: Nov 2007
Posts: 168
#2: Oct 8 '09

re: vector<int> to list of str


Looks like the general idea cannot change, but how you implement it is what will determine the performance. Maybe we see some implementation then see if it can move faster.

And do you want to insert a space (1) between every character?

Regards,

Alex
Member
 
Join Date: Oct 2009
Posts: 33
#3: Oct 8 '09

re: vector<int> to list of str


thanks for the reply.
yes i need to add space between the char.
here's the overview.. given v= 0123 and i need to convert it into string of
v= "[0 1 2 3]".

here's what i got so far
Expand|Select|Wrap|Line Numbers
  1. vector <int> v;
  2.  
  3. if (!this->v.empty() ){
  4.    for (int i=0; i<v.size(); i++){
  5.  
  6.      std::string s;
  7.      std::stringstream out;
  8.      out << v[i];
  9.      s = out.str();
  10.  
  11.     //of course i need some if statement in order to add 
  12.       "[" first then then spaces as well as a condition where no space 
  13.       between the last char with the closing bracket.
  14.  
  15.      std::ans += s
  16.  
  17.  

im pretty sure for loop will causes the code not to run faster in addition the conversion each int to each char.what can i do to improve it?
myusernotyours's Avatar
Familiar Sight
 
Join Date: Nov 2007
Posts: 168
#4: Oct 8 '09

re: vector<int> to list of str


You can use the string member function insert() to add the spaces and whatever.

Regards,

Alex.
Member
 
Join Date: Oct 2009
Posts: 33
#5: Oct 8 '09

re: vector<int> to list of str


thanks again.i'll try :)
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,382
#6: Oct 8 '09

re: vector<int> to list of str


Don't overlook the transform algorithm.

You may find all you need to write is a function that converts a single vector element. The algorithm will call your function using every element of the vector.
Reply