Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to vector in C++

Tags:

c++

string

vector

Is it possible to easily convert a string to a vector in C++?

string s = "12345"
vector<int>(s.begin(), s.end(), c => c - '0'); // something like that

The goal is to have a vector of ints like { 1, 2, 3, 4, 5 };

I don't want to use loops, I want to write a clear and simple code. (I know that beneath there will be some loop anyway).

The string is always a number.

like image 689
Patryk Golebiowski Avatar asked Dec 05 '22 03:12

Patryk Golebiowski


2 Answers

You could start with

string s = "12345"
vector<int> v(s.begin(), s.end())

and then use <algorithm>'s transform:

transform(
    s.begin(), s.end(), 
    s.begin(), 
    [](char a){return a - '0';});
like image 146
Ami Tavory Avatar answered Dec 26 '22 15:12

Ami Tavory


Maybe not exactly what you want (I don't know how to pull it off in the constructor):

string s = "12345";
vector<int> v;
for_each(s.begin(), s.end(), [&v](char c) {v.push_back(c - '0');});
like image 31
wcochran Avatar answered Dec 26 '22 14:12

wcochran