作者littleshan (我正在想要换什麽)
看板C_and_CPP
标题Re: [问题] 如何把字串中的数字取出(有空格相间)
时间Tue Jun 20 23:13:21 2017
C++ 其实提供非常多高阶函式把单调的回圈操作包装起来
以这个例子来说,切割字串可以用 istringstream 没错
但还可以搭配 istream_iterator 把资料流 (stream) 转成 iterator
有了 iterator 就可以搭配所有 STL 泛型函式使用
比如说把字串切割後存进 vector:
istringstream input(
"1 22 333 44 5");
istream_iterator<
int> begin(input);
istream_iterator<
int> end;
vector<
int> data;
data.insert(data.begin(), begin, end);
又,C++ 提供 std::accumulate,让你可以把 iterator 寻访过的每个元素加起来
这样就完全不需要另一个 vector 来存这些数字:
istringstream input(
"1 22 333 44 5");
istream_iterator<
int> begin(input);
istream_iterator<
int> end;
cout << accumulate(begin, end,
0) << endl;
// 405
只要把资料用 iterator 表示,就可以利用 STL 内大量的泛型函式
而且执行速度非常快。
※ 引述《pziyout (pziyout)》之铭言:
: : python可以把一串字串(或输入一大段字串用空白或逗号相间),转换後运算
: : 例如 " 10 20 30 123 " 变成-->" '10','20','30','123' "之类的,对数字进行运算
: : (利用 .split() + .append() 之类的~)
: : 但想请问C 或C++该如何进行?
: 使用 istringstream 与 vector
: #include <iostream>
: #include <sstream>
: #include <vector>
: using namespace std ;
: int main() {
: int i , n , s ;
: string foo = " 23 11 34 98 " ;
: istringstream istr(foo) ;
: vector<int> nums ;
: while ( istr >> n ) nums.push_back(n) ;
: cout << ( s = nums[0] ) ;
: for ( i = 1 ; i < nums.size() ; ++i ) {
: s += nums[i] ;
: cout << " + " << nums[i] ;
: }
: cout << " = " << s << endl ;
: return 0 ;
: }
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 153.156.42.69
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1497971604.A.D82.html
1F:→ a855341: 感谢L大解释方法 我晚点才有电脑来试试看 06/21 11:26
2F:→ a855341: 但有些东西开始看不懂了QAQ 新手上路 但还是非常感谢 06/21 11:26
3F:推 s25g5d4: 这作法太逆天 上次在 stackoverflow 看到整个人都高潮了 06/23 03:45
4F:→ Killercat: 这其实算很标准做法 没啥好逆天的,谁叫std::string 06/24 16:12
5F:→ Killercat: 连.split()这种东西都不提供 XD 06/24 16:12
6F:→ Killercat: 你去查how to split a string c++大概都会找到这方法 06/24 16:13
7F:推 steve1012: Standard library 应该要有split才对 最好Python 的全 07/01 16:07
8F:→ steve1012: 都抄来xD 07/01 16:07
9F:→ steve1012: 觉得很多部分标准实在进展太慢 07/01 16:08