計算機實習 === ``` cpp #include <bits/stdc++.h> // 加這行就不用 #include <iostream> #include <vector> ... ``` 1. 語法 * stringstream ``` cpp #include <sstream> ``` 宣告字串串流 ``` cpp stringstream ss; ``` 舉例: ``` cpp string s = "a20b301c3"; stringstream ss; ss << s; // 字串s丟到字串串流裡 char c; int n; while(ss >> c >> n) { // 把字串串流(ss)丟到字元c以及字元n,直到不能不能丟為止 cout << "mychar: " << c << endl; cout << "mynumber: " << n << endl; } ``` * 輸入含空格 ``` cpp string s; while(getline(cin, s)) { cout << s << endl; } /* 範例輸入 ACACAC AC We are the champion lalala */ ``` 如果前面先輸入了其他東西,要避免getline讀到換行 ``` cpp int n; string s; cin >> n; getline(cin, s); getline(cin, s); /* 10 nn cc uuuu */ ``` * array ``` cpp int a[105] = {}; // 宣告 + 初始化為 0 int b[105][55] = {}; // 二維陣列 int c[105][105][105] = {}; // 三維陣列 ``` ``` cpp void passArray(int a[]); void passArray2(int a[105][]); // 要給第一維的陣列大小 ``` ``` cpp // 陣列走訪 for(int i = 0; i < 105; i++) { for(int j = 0; j < 55; j++) { cout << b[i][j] << " "; } cout << endl; } ``` * vector ``` cpp #include <vector> ``` ``` cpp vector<int> v; // 宣告空的vector => v.size() == 0 for(int i = 0; i < 10; i++) { int in; cin >> in; v.push_back(in); } // push back完 v.size() == 10 vector<int> v2(10); for(int i = 0; i < 10; i++) { cin >> v[i]; } ``` * ctime ``` cpp #include <ctime> int main() { time_t now = time(0); tm *ltm = localtime(&now); cout << "year: " << 1900 + ltm->tm_year << endl; cout << "month: " << 1 + ltm->tm_mon << endl; cout << "day: " << ltm->tm_mday << endl; cout << "time: " << ltm->tm_hour << endl; cout << ltm->tm_min << endl; cout << ltm->tm_sec << endl; } ``` * 亂數 ``` cpp srand(time(0)); cout << rand() % 5 << endl; // 可能是 0, 1, 2, 3, 4 ``` * 指標 ``` cpp int a = 10; int *p = &a; // &a a的位址 cout << p << " " << *p << endl; ``` * reference ``` cpp int a = 10; int &b = a; // 你懂的 b += 5; cout << a << " " << b << endl; 2. 好玩的class ``` cpp class matrix { // 預設private public: matrix(int); // 建構子 friend istream &operator>> (istream &, matrix); } ``` 9. debug list * 超出陣列範圍 ``` cpp vector<int> v(10); cout << v[10]; // :(( ```