ebvtrnog
ebvtrnog

Reputation: 4367

Converting a string to vector in C++

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.

Upvotes: 5

Views: 2031

Answers (6)

Baum mit Augen
Baum mit Augen

Reputation: 50043

If your string gets so long that the performance hit from the double iteration matters, you can also do it in just a single pass:

vector<int> v;
v.reserve(str.size());
transform(begin(str), end(str), back_inserter(v),
    [](const auto &c){return c - '0';});

(Or with a C++11 lambda as already shown by others.)

Upvotes: 3

Achilles Rasquinha
Achilles Rasquinha

Reputation: 353

string s = "1234";
vector<int> v;
for(auto& i : s) v.push_back(i - '0');

One liner!

Upvotes: 1

Chris Drew
Chris Drew

Reputation: 15334

One loop with std::transform:

std::vector<int> v(s.size());
std::transform(s.begin(), s.end(), v.begin(), [](char c){return c - '0';});

Upvotes: 1

0x6773
0x6773

Reputation: 1116

Just two lines of mine :

vector<int> v(s.begin(), s.end());
for(auto& i : v) i = i - '0';

This is simplest one!

Upvotes: 0

Ami Tavory
Ami Tavory

Reputation: 76297

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';});

Upvotes: 7

wcochran
wcochran

Reputation: 10886

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');});

Upvotes: 4

Related Questions