Connecting Tech Pros Worldwide Help | Site Map

best method to convert list of string to vector<int>?

Member
 
Join Date: Oct 2009
Posts: 33
#1: Oct 12 '09
what's the best way to convert a list of string to a vector<int>?
what i have now is for loop and iterate each char in the string
Expand|Select|Wrap|Line Numbers
  1. string base="[0 3 ; 6 9 ; 12 15 ; 18 21]";
  2.  
  3.  
  4. //i have vector<int>row,vector < vector<int>row > mat;
  5. //what i want to do with the string is that everytime char != ";"
  6.  
  7. row.pushback(str that convert to int)
  8.  
  9. //do this when char == ";"
  10.  
  11. mat.pushback(row);
  12.  
but the problem with my code is that when it comes to more than one char for an int (eg "18") im not sure how to make it as (18) without making to many if statement?
and i cant find myself a better way for the code to operate fast.

any help would be great

thanks in advanced
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,148
#2: Oct 12 '09

re: best method to convert list of string to vector<int>?


You have a number of options, place you string into a stringstream then extract the data in the order you expect. One small problem of this is you kind of have to know exactly what you are getting out of the string before you get it, that is it is quite hard to deal with multiple formats for instance a matrix with a variable number of values on each row. If you don't know it's 2 values per row before you start you could have trouble, if you do know that then it is relatively easy to deal with differing numbers of rows based on the character read at the end of the row.

Expand|Select|Wrap|Line Numbers
  1.     string myString = "<123>";
  2.     istringstream ss(myString);
  3.     char sential;
  4.     int value;
  5.  
  6.     ss >> sential;
  7.  
  8.     if (sentinal == '<')
  9.     {
  10.         ss >> value;
  11.  
  12.         cout << value << endl;
  13.     }
  14.  
Alternatively there are various functions in the C standard library for converting strings to numbers strtol being my favourite.
Reply