C ++使用逗号分隔值将String转换为vector <int>

时间:2016-02-11 11:56:18

标签: c++ string optimization vector transform

我认为这个标题非常具有说明性,反正,这就是我要做的事情: 给定0到9之间的整数字符串的输入,每个数字用逗号分隔,将其转换为std :: vector。我已经知道了字符串的长度,因此矢量已经正确调整大小

我知道之前已经回答了,(How can I read and parse CSV files in C++?)但是我正在寻找一种没有外部库的解决方案(这是为了分配)。

1)此版本有效,但我认为这是非常基础的,我正在努力改进它

string line;
vector<int> numers;
int i=0;
...
for (string::iterator it=line.begin(); it<line.end(); it=it+2){ //I need to skip commas
    numbers[i]=*it-48;    

2)这是我认为会更好的表现,但无法让它发挥作用!

line.erase(std::remove(line.begin(), line.end(), ','), line.end());
transform(line.begin(),line.end(),numbers.begin(),[](const string &str){return stoi(str);});

此解决方案无法编译

有更好的主意吗?

0 个答案:

没有答案