文章目錄
函數
main方法要在其他方法/方法的signature下面
exit(1);
//立刻退出到 operating system
函數的缺省參數
可以給函數的參數設置默認值, 這樣調用方法的時候不傳參也可以
一個函數可以有多個缺省參數
缺省參數們只能寫在參數列表的最右邊
優點:
增加程序的擴展性
例如, 一個已有方法要擴展功能, 新增選擇顏色的參數, 那麼把顏色設置爲缺省參數可以讓以前調用它的方法不改變功能
範例:
//定義一個函數
void demo(int a, int b = 150, string c = "hahaha") {...}
//調用這個函數
demo(200);
demo(200, 99);
demo(200, 99, "hey hey");
switch case
只能用int或string
int type;
cin << type;
switch(type) {
case 1:
cout << "one";
break;
case 2:
cout << "two";
break;
default:
cout << "ohhh";
}
Vector
#include <vector>
vector<string> v;
v.push_back("hey");
string s = v[0];
int size = v.size();
創建方式
vector<string> v;
vector<string> v(10);
設定初始的size, 獲取index不會報錯
vector<string> v(10,"no name");
設定default value
方法
push_back(T t);
向末尾加一個元素
pop_back(T t);
從末尾取一個元素
at(index);
獲取某index的值
sort(vector.begin(), vector.end());
#include <algorithm>
Array
創建和賦值
int arr[] = {1, 2, 3, 4, 5};
string arr[5];
arr[0] = "hello world";
如果沒有初始化就讀取, 則讀取到的值是隨機數
所以建議都賦值爲0
只有以下情況是例外:
int arr[10] = {1, 2, 3}
其餘沒有賦值的用默認值0填充
方法
作爲參數傳遞時, 不需要&
就能引用對象併產生更改
獲得size的3種方法
1. int size = sizeof(arr)
2. sizeof(*arr);
使用指針獲取大小
3. 設定length的時候, 可以使用const, 這樣方便獲得size
const int size = 10;
string arr[size];
for(int i=0; i<size; i++) {
arr[i] = "student " + i;
}
2D Array
int arr[5][3] = {{1,2,3},{4,5,6}};
必須聲明row和column的值
如果想要作爲參數傳遞, 則定義參數時, 必須明確指定第二層array的數值
void test(int arr[][5]){...}
Map
虛幻四規範: 使用TMap
#include <map>
#define TMap std::map
Random numbers
#include <cstdlib>
- 需要seed, 可以使用當前時間毫秒值 (需要ctime)
srand(time(NULL));
int num = rand() % 10 + 1;
1到10
Time
#include <ctime>
time(NULL);
獲取當前時間毫秒值
auto
- 編譯期自動推斷變量是什麼類型的
TMap<char, bool> TempMap;
for(auto Letter : TempMap) {
...
}
fstream
#include <stream>
- 如果寫了多個讀寫方法, 則每次調用前清除buffer
cin.clear(); cin.sync();
ofstream
方法
put(char c)
寫入
ofstream out("c:\\data\\demo.txt", ios::out);
out << "hahahahah" << endl; //會抹掉舊數據
out.close();
累加寫入
- ofstream
- 聲明ofstream時, 改爲使用
ios::app
參數
ifstream
方法
get(char c);
取一個char放到參數裏getline(stream, str);
讀取
string path = "c:\\data\\demo.txt";
string content;
ifstream in(path.c_str(), ios::in); //參數必須是c string, 不可以是c++ string
if(!in) {
return; //文件不存在
}
while (!in.eof) { //如果是 end of file, 則 return true
in >> content;
cout << content << endl;
}
in.close();