Re: [問題] 如何把字串中的數字取出(有空格相間)
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://www.ptt.cc/bbs/C_and_CPP/M.1497971604.A.D82.html
→
06/21 11:26, , 1F
06/21 11:26, 1F
→
06/21 11:26, , 2F
06/21 11:26, 2F
推
06/23 03:45, , 3F
06/23 03:45, 3F
→
06/24 16:12, , 4F
06/24 16:12, 4F
→
06/24 16:12, , 5F
06/24 16:12, 5F
→
06/24 16:13, , 6F
06/24 16:13, 6F
推
07/01 16:07, , 7F
07/01 16:07, 7F
→
07/01 16:07, , 8F
07/01 16:07, 8F
→
07/01 16:08, , 9F
07/01 16:08, 9F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 4 篇):