简体   繁体   English

在C ++中将字符串转换为向量

[英]Converting a string to vector in C++

Is it possible to easily convert a string to a vector in C++? 是否可以在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 }; 目标是拥有像{ 1, 2, 3, 4, 5 };这样的整数向量{ 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 : 然后使用<algorithm>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 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.) (或者其他人已经显示过C ++ 11 lambda。)

Just two lines of mine : 我的两行:

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

This is simplest one! 这是最简单的一个!

One loop with std::transform : 一个带std::transform循环:

std::vector<int> v(s.size());
std::transform(s.begin(), s.end(), v.begin(), [](char c){return c - '0';});
string s = "1234";
vector<int> v;
for(auto& i : s) v.push_back(i - '0');

One liner! 一个班轮!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM