STL Hello World

平时要有容器、算法、迭代器的思维模式 容器提供迭代器,算法使用迭代器 // 算法 int count(int* begin, int* end, int val){ int n = 0; while(begin != end){ if(*begin == val){ n++; } begin++; } return n; } int main() { // 容器 int arr[] = {1, 3, 0, 5, 1, 3, 1, 0}; // 迭代器 int* begin = arr; int* end = *(&arr + 1); int n = count(begin, end, 1); cout << "count: " << n << endl; return 0; }

January 16, 2022 · 1 min · Rick Cui

文件操作

一、文件读写 文件输入流 ifstream 文件输出流 ofstream 文件输入输出流 fstream 文件的打开方式 文件流的状态 文件流的定位:文件指针(输入指针、输出指针) 二、文本文件 #include <iostream>#include <fstream>using namespace std; void ReadWriteFile(){ ifstream ifs("D:\\Users\\cui_z\\Desktop\\source.txt", ios::in); ofstream ofs("D:\\Users\\cui_z\\Desktop\\target.txt", ios::out | ios::app); if (!ifs) { cout << "输入文件打开失败" << endl; return; } if (!ofs) { cout << "输出文件打开失败" << endl; return; } char ch; while (ifs.get(ch)) { cout << ch; ofs << ch; } ifs.close(); ofs.close(); } 三、二进制文件 文本文件和二进制文件在计算机中都是以二进制的方式存储的 程序中的对象都是二进制存储的 Windows 中的文本文件换行符用 \r\n 表示,二进制是以 \n 存储,所以存储和显示时会做一下转换 Linux 中二进制和文本文件换行都是以 \n 存储和表示 class Person { private: int m_age; int m_id; public: Person():m_age(0), m_id(0){ } Person(int age, int id){ m_age = age; m_id = id; } ~Person() = default; void show(){ cout << "Age: " << m_age << " ID: " << m_id << endl; } }; void BinaryReadWrite(){ // 存储二进制 ofstream ofs("D:\\Users\\cui_z\\Desktop\\target....

January 16, 2022 · 1 min · Rick Cui

格式化输出

#include <iostream>#include <cstdlib>#include <cstring>#include <iomanip> // 控制符头文件using namespace std; // 格式化输出 void func(){ // 方式一:使用成员方法 int number = 10; cout << number << endl; cout.unsetf(ios::dec); // 八进制 cout.setf(ios::oct); cout.setf(ios::showbase); cout << number << endl; // 012 // 十六进制 cout.unsetf(ios::oct); cout.setf(ios::hex); cout << number << endl; // 0xa // 固定宽度 cout.width(10); cout.fill('*'); cout << number << endl; // *******0xa // 上面的设置只对当前输出有效,下次的输出格式要重新设置 cout.setf(ios::left); cout.width(10); cout....

January 16, 2022 · 1 min · Rick Cui

异常接口声明

C++ 异常 C++11 不再建议使用异常规范 // 异常规范 只能抛出 int float char 三种类型的异常 C++11以后不再建议使用 void func1() throw(int, float, char){ throw "string"; // terminate called after throwing an instance of 'char const*' } // 不能抛出任何类型的异常 OK void func2() throw(){ throw -1; // terminate called after throwing an instance of 'int' } // 可以抛出任何类型的异常 void func3(){ throw "error"; } int main() { try{ func1(); } catch(char const * e){ cout << e << endl; } catch(....

January 15, 2022 · 1 min · Rick Cui

栈解旋 Unwinding

异常被抛出后,从进入 try 块起到异常被抛出前,这期间在栈上构造的所有对象都会被自动析构,析构的顺序与构造的顺序相反。 与 return 类似 class Test{ public: Test(string name){ m_name = name; cout << m_name << "被构造了" << endl; } ~Test(){ cout << m_name << "被析构了" << endl; } private: string m_name; }; double func1(int x, int y){ Test t1("t1"), t2("t2"); if(y == 0){ throw y; } return x / y; } int main() { try{ Test t3("t3"), t4("t4"); func1(10, 0); } catch(int e){ cout << "除数为 " << e << endl; } return 0; } t3被构造了 t4被构造了 t1被构造了 t2被构造了 t2被析构了 t1被析构了 t4被析构了 t3被析构了 除数为 0

January 15, 2022 · 1 min · Rick Cui