stack即堆疊,一種先進后出的資料結構,
這次會在stack的基礎上講兩個實際應用,以及講一下stringstream,
直接上代碼!
1、stack基礎
#include<iostream> #include<stack> using namespace std; int main() { //構造 stack<int> s; //一般空參構造 //入堆疊 s.push(2); s.push(6); s.push(8); cout << s.size() << endl; //size:3 //stack不能遍歷,只能一個一個退堆疊 while (!s.empty()) { //輸出8 6 2 先進后出 cout << s.top() << ' '; //取堆疊頂,不會退堆疊 s.pop(); //退堆疊,無回傳值 } cout << endl << s.size() << endl; //size:0 return 0; }
2、進制轉換
#include<iostream> #include<stack> using namespace std; int main() { //進制轉換10->2 stack<int> s; int n; cin >> n; while (n) { s.push(n % 2); n /= 2; } while (!s.empty()) { n = n * 10 + s.top(); s.pop(); } cout << n << endl; return 0; }
3、以空格分割的字串逆序輸出
#include<iostream> #include<stack> #include<string> #include<sstream> using namespace std; int main() { //以空格分割的字串逆序輸出 string str; stack<string> s; getline(cin, str); //輸入一行字串 stringstream ss; //stringstream常用于string型別轉其他型別和切分以空格分割的字串,頭檔案<sstream> ss << str; while (ss >> str) s.push(str); while (!s.empty()) { cout << s.top(); s.pop(); if (s.size() != 0) cout << ' '; } cout << endl; return 0; }
4、string型別轉換
#include<iostream> #include<stack> #include<string> #include<sstream> using namespace std; int main() { //字串轉int/double,使用stringstream int intVal; double douVal; stringstream ss; string str1 = "268"; string str2 = "268.369"; ss << str1; ss >> intVal; ss.clear(); //一定要clear ss << str2; ss >> douVal; cout << double(intVal + douVal) << endl; //字串型別與int型別之間的轉換,使用函式 int n = stoi(str1); cout << 2 * n << endl; string str3 = to_string(n); cout << str1 + str3 << endl; return 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/43006.html
標籤:C++
下一篇:用C++實作:Sine之舞
