文章目录
函数
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();