gpt4 book ai didi

c++ - 使用 STL 解析整数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:48:34 26 4
gpt4 key购买 nike

这是解析整数并将它们存储在 vector 中的一种漂亮方法,前提是它们以空格分隔(来自 Split a string in C++? ):

#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>

int main() {
using namespace std;

string s = "3 2 1";
istringstream iss(s);
vector<int> tokens;

copy(istream_iterator<int>(iss),
istream_iterator<int>(),
back_inserter<vector<int> >(tokens));
}

是否可以在保持相似的情况下指定另一个分隔符(例如“,”)?

最佳答案

您可以使用正则表达式 (C++11) 概括字符串拆分。此函数通过在正则表达式上拆分字符串来标记您的字符串。

vector<string> split(const string& input, const regex& regex) {
sregex_token_iterator
first(input.begin(), input.end(), regex, -1),
last;
return vector<string>(first, last);
}

对于您的示例,要拆分 ',' 将 regex(",") 传递到函数中。

#include <iostream>
#include <string>
#include <regex>
#include <vector>

using namespace std;

vector<string> split(const string& input, const regex& regex) {
sregex_token_iterator
first(input.begin(), input.end(), regex, -1),
last;
return vector<string>(first, last);
}

int main() {

const regex r = regex(",");
const string s = "1,2,3";

vector<string> t = split(s, r);
for (size_t i = 0; i < t.size(); ++i) {

cout << "[" << t[i] << "] ";
}
cout << endl;

return 0;
}

关于c++ - 使用 STL 解析整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19383081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com