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.
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';});
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');});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With