作者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/m.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