Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse string to vector of int

Tags:

I have a string which contains some number of integers which are delimited with spaces. For example

string myString = "10 15 20 23"; 

I want to convert it to a vector of integers. So in the example the vector should be equal

vector<int> myNumbers = {10, 15, 20, 23}; 

How can I do it? Sorry for stupid question.

like image 256
mskoryk Avatar asked Dec 18 '13 13:12

mskoryk


People also ask

Is string a vector?

From a purely philosophical point of view: yes, a string is a type of vector. It is a contiguous memory block that stores characters (a vector is a contiguous memory block that stores objects of arbitrary types). So, from this perspective, a string is a special kind of vector.


1 Answers

You can use std::stringstream. You will need to #include <sstream> apart from other includes.

#include <sstream> #include <vector> #include <string>  std::string myString = "10 15 20 23"; std::stringstream iss( myString );  int number; std::vector<int> myNumbers; while ( iss >> number )   myNumbers.push_back( number ); 
like image 72
Abhishek Bansal Avatar answered Sep 18 '22 13:09

Abhishek Bansal