函数模板 #include <iostream> using namespace std;void swapInt (int &a,int &b) { int temp = a; a = b; b = temp; } void swapDouble (double &a,double &b) { int temp = a; a = b; b = temp; } template <class T > void mySwap (T &a,T &b) { T temp = a; a = b; b = temp; } int main () { int a=10 ; int b=20 ; mySwap <int >(a,b); cout<<"a=" << a<<";" <<"b=" <<b<<endl; double c=1.1 ; double d=2.2 ; mySwap (c,d); cout<<"c=" << c<<";" <<"d=" <<d<<endl; return 0 ; }
类模板 #include <iostream> #include <string> using namespace std;template <class T , class U >class Person { public : Person (T name,U age){ this ->name = name; this ->age = age; } T name; U age; void showPerson () { cout << "name:" << this ->name << "\n" << "age:" << this ->age << endl; } }; int main () { Person<string,int >p ("张三" ,18 ); p.showPerson (); return 0 ; } template <class T1 ,class T2 >class Person { public : Person (T1 name, T2 age){ this ->name = name; this ->age = age; } void showPerson () { cout << "name:" << this ->name << "\n" << "age:" << this ->age << endl; } T1 name; T2 age; }; void printPerson1 (Person<string,int > &p) { p.showPerson (); } void test1 () { Person<string,int >p ("lisi" ,19 ); printPerson1 (p); } template <class T1,class T2>void printPerson2 (Person<T1,T2> &p) { p.showPerson (); cout << "T1的类型为:" << typeid (T1).name () << endl; cout << "T2的类型为:" << typeid (T2).name () << endl; } void test2 () { Person<string,int >p ("lisi" ,20 ); printPerson2 (p); } template <class T>void printPerson3 (T &p) { p.showPerson (); } void test3 () { Person<string,int >p ("lisi" ,21 ); printPerson3 (p); } template <class T >class Base { T m; }; class Son1 :public Base<int >{}; template <class T1 ,class T2 >class Son2 :public Base<T1>{ T2 obj; }; #include <iostream> #include <string> using namespace std;template <class T3 ,class T4 >class Person1 { public : Person1 (T3 name,T4 age); void showPerson () ; T3 name; T4 age; }; template <class T3 ,class T4 >Person1<T3,T4>::Person1 (T3 name,T4 age){ this ->name=name; this ->age=age; } template <class T3 ,class T4 >void Person1<T3,T4>::showPerson (){ cout<< "sb" << endl; }
函数对象 #include <iostream> #include <string> #include <functional> using namespace std;class Myadd { public : int operator () (int v1,int v2) { return v1+v2; } }; void test01 () { Myadd myadd; cout << myadd (10 ,20 ) << endl ; } class Myprint { public : Myprint (){ this ->count = 0 ; } void operator () (string s) { cout << s << endl; this ->count++; } int count; }; void test02 () { Myprint myprint; myprint ("aaaa" ); myprint ("aaaa" ); myprint ("aaaa" ); cout << "Myprint调用的次数是" << myprint.count << "次" << endl; } void doPrint (Myprint &mp,string s) { Myprint myprint; myprint (s); } int main () { Myprint mp2; doPrint (mp2,"cnm" ); return 0 ; }
读、写文件 #include <iostream> #include <fstream> using namespace std;class Person { public : char name[64 ]; int age; }; int main () { ifstream ifs; ifs.open ("person.txt" ,ios::in | ios::binary); if (!ifs.is_open ()){ cout << "打开失败" << endl; return 0 ; } Person p; ifs.read ((char *)&p,sizeof (p)); cout << "姓名:" << p.name << "\n" << "年龄:" << p.age << endl; ifs.close (); }
#include <iostream> #include <fstream> using namespace std;int main () { ofstream ofs; ofs.open ("test01.txt" ,ios::out); ofs << "name:kongjiangang" << endl; ofs << "gender:male" << endl; ofs.close (); }
#include <iostream> #include <fstream> using namespace std;class Person { public : char name[64 ]; int age; }; int main () { ofstream ofs; ofs.open ("person.txt" ,ios::out | ios::binary); Person p = {"张三" ,18 }; ofs.write ((const char *)&p,sizeof (p)); ofs.close (); }
STL stl general #include <iostream> #include <vector> #include <algorithm> using namespace std;void myPrint (int val) { cout << val << endl; } void test01 () { vector<int > v; v.push_back (10 ); v.push_back (20 ); v.push_back (30 ); v.push_back (40 ); vector<int >::iterator itBegin = v.begin (); vector<int >::iterator itEnd = v.end (); while (itBegin != itEnd) { cout << *itBegin << endl; itBegin++; } for (vector<int >::iterator it = v.begin (); it != v.end (); it++) { cout << *it << endl; } for_each(v.begin (),v.end (),myPrint); } void test02 () { vector< vector<int > > v; vector<int > v1; vector<int > v2; vector<int > v3; vector<int > v4; for (int i=0 ;i<4 ;i++){ v1.push_back (i+1 ); v2.push_back (i+1 ); v3.push_back (i+1 ); v4.push_back (i+1 ); } v.push_back (v1); v.push_back (v2); v.push_back (v3); v.push_back (v4); for (vector<vector<int > >::iterator iterator=v.begin ();iterator!=v.end ();iterator++){ for (vector<int >::iterator vit=(*iterator).begin ();vit!=(*iterator).end ();vit++) cout<< (*vit) << endl; } } int main () { test01 (); cout << "\n" << endl; test02 (); return 0 ; }
vector #include <iostream> #include <vector> using namespace std;int main () { return 0 ; }
priority_queue class Solution {public : class mycomparison { public : bool operator () (const pair<int , int >& lhs, const pair<int , int >& rhs) { return lhs.second > rhs.second; } }; vector<int > topKFrequent (vector<int >& nums, int k) { map<int , int > mp; for (int e: nums) mp[e]++; priority_queue<pair<int , int >, vector<pair<int , int >>, mycomparison> pri_que; for (auto i = mp.begin (); i != mp.end (); i ++){ pri_que.push (*i); if (pri_que.size () > k) pri_que.pop (); } vector<int > res (k) ; for (int i = k - 1 ; i >= 0 ; i--) { res[i] = pri_que.top ().first; pri_que.pop (); } return res; } };
#define pii pair<int, int> class Solution {public : int kthSmallest (vector<vector<int >>& matrix, int k) { int n = matrix.size (), res = 0 ; auto comp = [&](pii& l, pii& r){ return matrix[l.first][l.second] > matrix[r.first][r.second];}; priority_queue<pii, vector<pii>, decltype (comp)> q (comp); for (int i = 0 ; i < n; ++i) q.emplace (i, 0 ); while (--k){ auto [i, j] = q.top (); q.pop (); if (j != n-1 ) q.emplace (i, j+1 ); } auto [i, j] = q.top (); return matrix[i][j]; } };
list #include <iostream> #include <stack> #include <algorithm> using namespace std;int main () { return 0 ; }
map #include <iostream> #include <map> #include <algorithm> using namespace std;int main () { return 0 ; }
set #include <iostream> #include <set> #include <algorithm> using namespace std;int main () { return 0 ; }
stack #include <iostream> #include <stack> #include <algorithm> using namespace std;int main () { return 0 ; }
queue #include <iostream> #include <stack> #include <algorithm> using namespace std;int main () { return 0 ; }
deque deque ();deque (int nSize); deque (int nSize,const T& t);deque (const deque &); void push_front (const T& x) ; void push_back (const T& x) ; iterator insert (iterator it,const T& x) ; void insert (iterator it,int n,const T& x) ; void insert (iterator it,const_iterator first,const_iterator last) ; iterator erase (iterator it) ; iterator erase (iterator first,iterator last) ; void pop_front () ; void pop_back () ; void clear () ; reference at (int pos) ; reference front () ; reference back () ; iterator begin () ; iterator end () ; reverse_iterator rbegin () ; reverse_iterator rend () ; bool empty () const ; int size () const ; int max_size () const ; void swap (deque&) ; void assign (int n,const T& x) ;
string #include <iostream> #include <string> using namespace std;int main () { return 0 ; }
刷题输入输出 int a,b;cin>>a>>b; cout<<a+b<<endl;
char a[20 ];cin>>a; cout<<a<<endl;
char ch;cin.get (ch); cout<<ch<<endl; char ch;ch=getchar (); cout<<ch<<endl;
char m[20 ];cin.getline (m,5 ); cout<<m<<endl; string st ; cout<<"Input st:" ; getline (cin,st);cout<<st<<endl;
char m[20 ];gets (m); cout<<m<<endl;
刷题常用函数 to_string(int x) class Solution {public : bool isPalindrome (int x) { string s = to_string (x); string s1 = s; reverse (s.begin (), s.end ()); return s == s1; } };
stoi(string s) string 类型转为 int 类型
reverse(iterator begin, iterator end) class Solution {public : bool isPalindrome (int x) { string s = to_string (x); string s1 = s; reverse (s.begin (), s.end ()); return s == s1; } };
islower/ isupper/isalpha/isdigit isalnum(char ch) class Solution {public : bool isPalindrome (string s) { string sgood; for (char ch: s) { if (isalnum (ch)) { sgood += tolower (ch); } } string sgood_rev (sgood.rbegin(), sgood.rend()) ; return sgood == sgood_rev; } };
tolower(char ch)/toupper(char ch) /tolower(string s)/toupper(string s) class Solution {public : bool isPalindrome (string s) { string sgood; for (char ch: s) { if (isalnum (ch)) { sgood += tolower (ch); } } string sgood_rev (sgood.rbegin(), sgood.rend()) ; return sgood == sgood_rev; } };
next_permutation(iterator begin, iterator end) 函数将按字母表顺序生成给定序列的下一个较大的排列,直到整个序列为降序为止。
prev_permutation(iterator begin, iterator end) 函数与之相反,是生成给定序列的上一个较小的排列。
long int stol(const string&str) class Solution {public : int nextGreaterElement (int n) { auto tmp = to_string (n); return next_permutation (tmp.begin (), tmp.end ()) && stol (tmp) <= INT_MAX ? stol (tmp) : -1 ; } };
此函数将在函数调用中作为参数提供的字符串 转换为long int。
sort && stable_sort sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使用stable_sort
函数,这里不过多介绍
由于在排序过程中涉及到元素交换 等操作,所以sort函数仅支持可随机访问 的容器,如数组, string, vector, deque等
方式一(默认) void sort (RandomAccessIterator first, RandomAccessIterator last);
sort (arr.begin (), arr.end ());
方式二(自定义) void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
实现降序排列,需传入第三个参数–比较函数,greater<type>()
,这里的元素为int
类型,即函数为 greater<int>()
;
sort (arr.begin (), arr.end (), greater <int >());
lower_bound/ upper_bound ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val) ;ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val, Compare comp) ;
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val) ;ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val, Compare comp) ;
replace 请实现一个函数,把字符串 s
中的每个空格替换成”%20”。
class Solution {public : string replaceSpace (string s) { for (int i = 0 ; i < s.size (); i ++) if (s[i]==' ' ) s.replace (i, 1 , "%20" ); return s; } };
C++ Primer Plus
cout.put('A');
与 cout << 'A';
区别 : 前者打印A的ASCII码, 后者打印A
const Month = 12 这样便可以在程序中使用Month而不是12了
强制转换的语法有两种: (typeName) value
和typeName (value)
C++11新增:static_cast<typeName> value
在初始化声明中,如果使用auto,而不指定变量的类型,编译器将把变量的类型设置成 与初始值相同
数组:
声明 typeName arrayName[arraySize];
其中arraySize
不能为变量。
初始化时可以 int a[2]={1,2}
也可以 int a[3] ={1,2}
【长度为3,第三个元素默认为0】同样可以int a[] = {1,2}
【长度为2】
C++11初始化数组时可以省略 = ;其次 int a = {}
代表将a初始化为全0;最后 列表初始化禁止缩窄转换 如 不允许long a[] = {3, 1.2,1.3}
。
字符串string
本质上是以'\0'
结尾的char数组
char a = 'A'
正确 char a = "A"
错误 因为” “是字符串 而’ ‘是字符
每次读取一行字符串输入: cin.getline(name, 20)
// 使用getline( )将姓名读入到一个包含20个元素的name数组中
共用体:
union a { int int_val; long long_val; double double_val; }; a pail; pail.int_val = 5 ; pail.double_val = 5.20
结构体 enum color={red, green, blue}
red等叫枚举量,分别对应0-2 也可以这样初始化enum a ={first, second = 100, third}
这里,first在默认情况下为0。后面没有被初始化的枚举量的值将比 其前面的枚举量大1。因此,third的值为101。 也可以这样创建:enrm a ={aa, aaa = 0, bb, bbb = 1}
其中,aa和aaa都为0,bb和bbb都为1。
指针的写法可以: int* ptr
或int *ptr
或int*ptr
int * ptr;ptr = 0xB8000000 ; ptr = (int *) 0xB8000000 ; int *ptr = new int ; delete ptr; int a = 5 ;int *ptr = &a;delete ptr; char *p1 = new char ;char *p2 = new char [1000 ];*(p1 + 4 ) = 12 ; delete p1;delete [] p2;int * ar = new arr[10 ];arr[i] = *(ar + i); &arr[i] = ar + i; 结构体对象访问成员用. 结构体指针访问成员用->
原型描述了函数到编译器的接口,也就是说,它将函数返回值的类 型(如果有的话)以及参数的类型和数量告诉编译器。
原型语法: void funcA(int, char);
函数原型的作用:
1.帮助编译器正确处理函数返回值;
2.帮助 编译器检查使用的参数数目是否正确;
3.帮助编译器检查使用的参数类型是否正确。如果不正确,则转换为正确 的类型(如果可能的话)
用const
保护数组: 使用普通参数时,这种保护将 自动实现,这是由于C++按值传递数据,而且函数使用数据的副本。然而,接受数组名的函数将使用原始数据,为防止函数无意中修改数组的内容,可在声明形参时 使用关键字const
如 void noChangeArr(const int arr[], int n);
原型里也要加const
指针和const
:
int a = 10 ;const int * var1 = &a; *var1 = 20 ; var = &b; int a = 10 ;int * const var2; *var2 = 20 ; var2 = b; const int * const var3;
当且仅当声明函数的形参时,下面两个声明才是等价的 typeName arr[]
与typeName *arr
假设要将字符串作为参数 传递给函数,则表示字符串的方式有3种:
char数组;
被设置为字符串的地址的char指针。
用引号括起的字符串常量(也称字符串字面值)
上述3种选择的类型都是char指针(准确的说是char*),因此可以将其作为字符串处理函数的参数。
char ghost[15 ] = "galloping" ;char * str = "galloping" ;int n1 = strlen (ghost); int n2 = strlen (str); int n3 = strlen ("galloping" );
函数指针:
获取函数的地址:只要使用函数名(后面不跟参数)即可。如:think()是一个函数,则think就是该函数的地址。
如果要将函数作为参数进行传递,必须传递函数名。
函数括号中的形参可有可无,视情况而定。
与指针函数区别开来,指针函数是返回值类型为指针的函数
函数指针的声明方法为: 返回值类型 ( * 指针变量名) ([形参列表]); int func (int x) ; int (*f) (int x); f=func; f = &func;
用typedef 对函数指针进行简化: typedef double real;typedef char (*pFun) (int ) char glFun (int a) {return ;} void main () { pFun =glFun; (*pFun)(2 ); }
内联函数:编译器将使用相应的函数代码替换函数调用。[文本替换,会带来内存的占用]
使用内联函数的措施:
在函数声明前加上关键字inline;
在函数定义前加上关键字inline。
引用变量:
int rats;int & rodents = rats;
类和对象 Example1 #include <iostream> #include <string> using namespace std;const double PI = 3.14 ;class Circle {public : int radius; double calulateZC () { return 2 * radius * PI; } }; class Student {public : string sname; string sid; void setID (string id) { sid = id; } void setName (string name) { sname = name; } void printInfo () { cout << "学号:" << sid << "\t姓名:" << sname << endl; } }; int main () { Circle c1; c1.radius = 3 ; cout << "半径为" << c1.radius << "的圆,周长为" << c1.calulateZC () << endl; Student stu1; stu1.sid = "10086" ; stu1.sname = "移动" ; stu1.printInfo (); Student stu2; stu2.setID ("110" ); stu2.setName ("刑警队" ); stu2.printInfo (); return 0 ; }
正方体 #include <iostream> #include <string> using namespace std;class Cube {private : int length = 0 ; int width = 0 ; int height = 0 ; public : void set_LWH (int l, int w, int h) { length = l; width = w; height = h; } int caculateArea () { if ((length == 0 ) || (width == 0 ) || (height == 0 )) { cout << "\aYou must set the length, width and height of cube by function: set_LWH ." << endl; return 0 ; } else return 2 *(length * width + width * height + length * height); } int caculateVolume () { if ((length == 0 ) || (width == 0 ) || (height == 0 )) { cout << "\aYou must set the length, width and height of cube by function: set_LWH ." << endl; return 0 ; } else return length * width * height; } void isSame (Cube &c) { if (caculateVolume () == c.caculateVolume ()) cout << "两个立方体体积相等!" << endl; else cout << "两个立方体体积不相等!" << endl; } }; void isEqual (Cube &c1, Cube &c2) { if (c1.caculateVolume () == c2.caculateVolume ()) cout << "两个立方体体积相等!" << endl; else cout << "两个立方体体积不相等!" << endl; } int main () { Cube cube1; cube1.set_LWH (2 , 3 , 4 ); cout << "面积为:" << cube1.caculateArea () << endl; cout << "体积为:" << cube1.caculateVolume () << endl; Cube cube2; cube2.set_LWH (2 , 4 , 3 ); cout << "面积为:" << cube2.caculateArea () << endl; cout << "体积为:" << cube2.caculateVolume () << endl; isEqual (cube1, cube2); cube2.isSame (cube1); return 0 ; }
析构 #include <iostream> #include <string> using namespace std;class Person {public : int age = 0 ; Person () { cout << "无参构造函数!" << endl; } Person (int a) { age = a; cout << "有参构造函数!" << endl; } Person (const Person& p) { age = p.age; cout << "这是拷贝构造函数!\t" << age << endl; } ~Person () { cout << "这是析构函数!" << endl; } }; void test01 () { Person p1; Person p2 (10 ) ; Person p3 (p2) ; } void test02 () { Person p1; Person p2 = Person (10 ); Person p3 = Person (p2); } void test03 () { Person p1; Person p2 = 10 ; Person p3 = p2; } int main () { test03 (); return 0 ; }
常函数
常函数内不可以修改成员属性
成员属性声明时加关键字mutable后,在常函数中依然可修改
#include <iostream> using namespace std;class Person {public : void showCls () const { this ->m_height = 100.0 ; } void showAge () {} int m_age; mutable float m_height; }; int main () { Person p; p.showCls (); const Person p1; p1.m_height = 20.0 ; p1.showCls (); return 0 ; }
运算符重载 #include <iostream> using namespace std;class Person {}; ostream& operator <<(ostream &out, Person &p) { out << "class Person" ; return out; }
#include <iostream> using namespace std;class Myinteger { friend ostream& operator <<(ostream& cout, Myinteger myint); int m_Num; public : Myinteger () { m_Num = 0 ; } Myinteger& operator ++() { ++m_Num; return *this ; } Myinteger operator ++(int ) { Myinteger temp = *this ; m_Num++; return temp; } Myinteger& operator --() { --m_Num; return *this ; } Myinteger operator --(int ) { Myinteger temp = *this ; m_Num--; return temp; } }; ostream& operator <<(ostream& cout, Myinteger myint) { cout << myint.m_Num; return cout; } int main () { Myinteger myint; cout << myint << endl; cout << ++myint << endl; cout << myint++ << endl; cout << myint << endl; cout << --myint << endl; cout << myint << endl; cout << myint-- << endl; cout << myint << endl; }
= 重载 #include <iostream> using namespace std;class Person {public : Person (int age) { m_age = new int (age); } ~Person () { if (m_age != NULL ) { delete m_age; m_age = NULL ; } } Person& operator =(Person& p) { if (this ->m_age != NULL ) { delete m_age; m_age = NULL ; } m_age = new int (*p.m_age); return *this ; } int *m_age; }; int main () { Person p1 (18 ) ; Person p2 (20 ) ; Person p3 (30 ) ; p3 = p2 = p1; cout << *p1.m_age << endl; cout << *p2.m_age << endl; cout << *p3.m_age << endl; return 0 ; }
仿函数 #include <iostream> #include <string> using namespace std;class MyPrint {public : void operator () (string test) { cout << test << endl; } }; int main () { MyPrint myprint; myprint ("hello world." ); return 0 ; }
继承 #include <iostream> using namespace std;class Person {public : void showGrade () {cout << "年级:" << m_grade << "年级" << endl;} private : int m_grade = 3 ; }; class Man :public Person {public : void showSex () { cout << "男生" << endl; } }; class Woman :public Person {public : void showSex () { cout << "女生" << endl; } }; int main () { Man m; m.showGrade (); m.showSex (); Woman w; w.showGrade (); w.showSex (); return 0 ; }
#include <iostream> using namespace std;class Base {public : int m_a; protected : int m_b; private : int m_c; }; class Son1 :public Base { void func () { m_a = 10 ; m_b = 10 ; } }; class Son2 :protected Base { void func () { m_a = 10 ; m_b = 10 ; } }; class Son3 :private Base { void func () { m_a = 100 ; m_b = 100 ; } }; class grandson3 :public Son3 { void func () { } }; int main () { Son1 s1; s1.m_a = 100 ; Son2 s2; Son3 s3; return 0 ; }
计算器 #include <iostream> using namespace std;class Caculator1 {private : int num1; int num2; string flag; private : int add () { return num1 + num2; } int minus () { return num1 - num2; } int times () { return num1 * num2; } int divided () { return num1 / num2; } public : Caculator1 (int n1, string f, int n2) :num1 (n1), flag (f), num2 (n2) {} void show () { if (flag == "+" ) cout << num1 << flag << num2 << "=" << add () << endl; if (flag == "-" ) cout << num1 << flag << num2 << "=" << minus () << endl; if (flag == "*" ) cout << num1 << flag << num2 << "=" << times () << endl; if (flag == "/" ) cout << num1 << flag << num2 << "=" << divided () << endl; } }; class AbstractCaculator {public : virtual int getResult () { return 0 ; } int m_Num1; int m_Num2; }; class AddCaculator :public AbstractCaculator {public : int getResult () { return m_Num1 + m_Num2; } }; class MinusCaculator :public AbstractCaculator {public : int getResult () { return m_Num1 - m_Num2; } }; class MultiplyCaculator :public AbstractCaculator {public : int getResult () { return m_Num1 * m_Num2; } }; void test01 () { int num1, num2; string flag; cin >> num1 >> flag >> num2; Caculator1 c (num1, flag, num2) ; c.show (); } void test02 () { AbstractCaculator* abc = new AddCaculator; abc->m_Num1 = 10 ; abc->m_Num2 = 20 ; cout << abc->m_Num1 << " + " << abc->m_Num2 << " = " << abc->getResult () << endl; delete abc; abc = new MinusCaculator; abc->m_Num1 = 10 ; abc->m_Num2 = 20 ; cout << abc->m_Num1 << " - " << abc->m_Num2 << " = " << abc->getResult () << endl; delete abc; abc = new MultiplyCaculator; abc->m_Num1 = 10 ; abc->m_Num2 = 20 ; cout << abc->m_Num1 << " * " << abc->m_Num2 << " = " << abc->getResult () << endl; delete abc; } int main () { test02 (); return 0 ; }
电脑 #include <iostream> #include <string> #include <iomanip> using namespace std;class AbsCPU {public : virtual void caculate () = 0 ; }; class AbsVideoCard {public : virtual void show () = 0 ; }; class AbsMemory {public : virtual void storage () = 0 ; } class IntelCPU :public AbsCPU {public : void caculate () { cout << "Intel CPU is caculating." << endl; } }; class IntelVideoCard :public AbsVideoCard {public : void show () { cout << "Intel video card is working." << endl; } }; class IntelMemory :public AbsMemory {public : void storage () { cout << "Intel memory is to storage." << endl; } }; class LenovoCPU :public AbsCPU {public : void caculate () { cout << "Lenovo CPU is caculating." << endl; } }; class LenovoVideoCard :public AbsVideoCard {public : void show () { cout << "Lenovo video card is working." << endl; } }; class LenovoMemory :public AbsMemory {public : void storage () { cout << "Lenovo memory is to storage." << endl; } }; class Computer {public : Computer (string* desc, AbsCPU *cpu, AbsVideoCard *vc, AbsMemory *mem) :m_desc (desc), m_cpu (cpu), m_vc (vc), m_mem (mem){} ~Computer () { if (m_cpu != NULL ) { delete m_cpu; m_cpu = NULL ; } if (m_vc != NULL ) { delete m_vc; m_cpu = NULL ; } if (m_mem != NULL ) { delete m_mem; m_cpu = NULL ; } if (m_desc != NULL ) { delete m_desc; m_desc = NULL ; } } void makeup () { cout << setw (25 ) << setfill ('*' ) <<"开始组装" << *m_desc << setw (15 ) << "" << endl; m_cpu->caculate (); m_vc->show (); m_mem->storage (); cout << setw (30 ) << setfill ('*' ) << "组装完成" << setw (20 ) << "" << endl; } private : string* m_desc; AbsCPU* m_cpu; AbsVideoCard* m_vc; AbsMemory* m_mem; }; void test003 () { AbsCPU* intelCPU = new IntelCPU; AbsVideoCard* intelVideoCard = new IntelVideoCard; AbsMemory* intelMemory = new IntelMemory; string* computer_name1 = new string ("Intel电脑" ); Computer* computer1 = new Computer (computer_name1, intelCPU, intelVideoCard, intelMemory); computer1->makeup (); delete computer1; AbsCPU* lenovoCPU = new LenovoCPU; AbsVideoCard* lenovoVideoCard = new LenovoVideoCard; AbsMemory* lenovoMemory = new LenovoMemory; string* computer_name2 = new string ("Lenovo电脑" ); Computer* computer2 = new Computer (computer_name2, lenovoCPU, lenovoVideoCard, lenovoMemory); computer2->makeup (); delete computer2; string* computer_name3 = new string ("混搭电脑 " ); Computer* computer3 = new Computer (computer_name3, new IntelCPU, nw LenovoVideoCard, new LenovoMemory); computer3->makeup (); delete computer3; } int main () { test003 (); return 0 ; }
读写文件 写
#include <iostream> #include <fstream> using namespace std;int main () { fstream ofs; ofs.open ("test.txt" , ios::out); ofs << "姓名:张三" << endl; ofs << "性别:男" << endl; ofs << "年龄:20" << endl; ofs.close (); return 0 ; } #include <iostream> #include <fstream> using namespace std;int main () { fstream ofs; ofs.open ("水仙花数.txt" , ios::out); int num = 100 ; while (num < 1000 ) { int hunderd = num / 100 ; int ten = num % 100 / 10 ; int n = num % 10 ; if (pow (hunderd, 3 ) + pow (ten, 3 ) + pow (n, 3 ) == num) { ofs << num << "\t" ; } num++; } ofs.close (); return 0 ; }
读
#include <iostream> #include <fstream> using namespace std;int main () { fstream ifs; ifs.open ("test.txt" , ios::in); char buffer[1024 ]; char c; while ((c = ifs.get ()) != EOF) { cout << c; } return 0 ; }
二进制方式读写文件 写
#include <iostream> #include <fstream> using namespace std;class Person {public : char m_Name[64 ]; int m_Age; }; void test01 () { fstream ofs ("person.txt" , ios::out | ios::binary) ; Person p = { "张三" , 18 }; ofs.write ((const char *)&p, sizeof (Person)); ofs.close (); } int main () { test01 (); return 0 ; }
读
#include <iostream> #include <fstream> using namespace std;class Person {public : char m_Name[64 ]; int m_Age; }; int main () { fstream ifs ("person.txt" , ios::in | ios::binary) ; if (!ifs.is_open ()) { cout << "打开文件失败" << endl; return 0 ; } Person p; ifs.read ((char *)&p, sizeof (Person)); cout << "姓名:" << p.m_Name << "\t年龄:" << p.m_Age << endl; ifs.clear (); return 0 ; }
多进程 1. 并行计算 Pi 的值 以下代码展示了如何使用多进程并行计算 Pi 的值。该程序将计算过程分为多个进程并行执行,最后将结果合并得到 Pi 的值。
#include <iostream> #include <cstdlib> #include <cmath> #include <unistd.h> #include <sys/wait.h> using namespace std;const int NUM_PROCESSES = 4 ; const int NUM_ITERATIONS = 1000000000 ; double calculate_pi (int start, int end) { double sum = 0 ; for (int i = start; i < end; i++) { double x = (i + 0.5 ) / NUM_ITERATIONS; sum += 4.0 / (1.0 + x * x); } return sum; } int main () { pid_t pid; double pi = 0 ; for (int i = 0 ; i < NUM_PROCESSES; i++) { pid = fork(); if (pid == 0 ) { double result = calculate_pi (i * NUM_ITERATIONS / NUM_PROCESSES, (i + 1 ) * NUM_ITERATIONS / NUM_PROCESSES); exit (result); } else if (pid < 0 ) { cerr << "Error: fork failed." << endl; exit (1 ); } } for (int i = 0 ; i < NUM_PROCESSES; i++) { int status; pid_t child_pid = wait (&status); if (WIFEXITED (status)) pi += WEXITSTATUS (status); else { cerr << "Error: child process " << child_pid << " failed." << endl; exit (1 ); } } cout << "Pi is approximately " << pi / NUM_ITERATIONS << endl; return 0 ; }
2.生产者消费者模型 #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <unistd.h> #include <sys/mman.h> #include <sys/wait.h> using namespace std;const int BUFFER_SIZE = 10 ; const int NUM_ITEMS = 100 ; struct buffer { int count; int data[BUFFER_SIZE]; }; void produce_item (int item) { cout << "Producing item: " << item << endl; } void consume_item (int item) { cout << "Consuming item: " << item << endl; } void producer (buffer* buf) { for (int i = 0 ; i < NUM_ITEMS; i++) { while (buf->count == BUFFER_SIZE) { sleep (1 ); } produce_item (i); buf->data[buf->count++] = i; } } void consumer (buffer* buf) { for (int i = 0 ; i < NUM_ITEMS; i++) { while (buf->count == 0 ) { sleep (1 ); } int item = buf->data[--buf->count]; consume_item (item); } } int main () { buffer* buf = (buffer*)mmap (NULL , sizeof (buffer), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1 , 0 ); if (buf == MAP_FAILED) { cerr << "Error: mmap failed." << endl; exit (1 ); } buf->count = 0 ; pid_t pid = fork(); if (pid == 0 ) { consumer (buf); exit (0 ); } else if (pid < 0 ) { cerr << "Error: fork failed." << endl; exit (1 ); } producer (buf); int status; pid_t child_pid = wait (&status); if (WIFEXITED (status)) { cout << "Child process " << child_pid << " exited with status " << WEXITSTATUS (status) << endl; } else { cerr << "Error: child process " << child_pid << " failed." << endl; exit (1 ); } munmap (buf, sizeof (buffer)); return 0 ; }
多线程 1.并行计算Pi的值 #include <iostream> #include <cmath> #include <thread> #include <vector> using namespace std;const int NUM_THREADS = 4 ; const int NUM_ITERATIONS = 1000000000 ; double calculate_pi (int start, int end) { double sum = 0 ; for (int i = start; i < end; i++) { double x = (i + 0.5 ) / NUM_ITERATIONS; sum += 4.0 / (1.0 + x * x); } return sum; } int main () { vector<thread> threads; double pi = 0 ; for (int i = 0 ; i < NUM_THREADS; i++) { threads.emplace_back ([i, &pi]() { double result = calculate_pi (i * NUM_ITERATIONS / NUM_THREADS, (i + 1 ) * NUM_ITERATIONS / NUM_THREADS); pi += result; }); } for (auto & t : threads) t.join (); cout << "Pi is approximately " << pi / NUM_ITERATIONS << endl; return 0 ; }
2.线程池 #ifndef THREADPOOL_H #define THREADPOOL_H #include <list> #include <cstdio> #include <exception> #include <pthread.h> #include "locker.h" template <typename T>class threadpool {public : threadpool (int thread_number = 8 , int max_requests = 10000 ); ~threadpool (); bool append (T* request) ; private : static void * worker (void * arg) ; void run () ; private : int m_thread_number; pthread_t * m_threads; int m_max_requests; std::list< T* > m_workqueue; locker m_queuelocker; sem m_queuestat; bool m_stop; }; template < typename T >threadpool< T >::threadpool (int thread_number, int max_requests) : m_thread_number (thread_number), m_max_requests (max_requests), m_stop (false ), m_threads (NULL ) { if ((thread_number <= 0 ) || (max_requests <= 0 ) ) { throw std::exception (); } m_threads = new pthread_t [m_thread_number]; if (!m_threads) { throw std::exception (); } for ( int i = 0 ; i < thread_number; ++i ) { printf ( "create the %dth thread\n" , i); if (pthread_create (m_threads + i, NULL , worker, this ) != 0 ) { delete [] m_threads; throw std::exception (); } if ( pthread_detach ( m_threads[i] ) ) { delete [] m_threads; throw std::exception (); } } } template < typename T >threadpool< T >::~threadpool () { delete [] m_threads; m_stop = true ; } template < typename T >bool threadpool< T >::append ( T* request ){ m_queuelocker.lock (); if ( m_workqueue.size () > m_max_requests ) { m_queuelocker.unlock (); return false ; } m_workqueue.push_back (request); m_queuelocker.unlock (); m_queuestat.post (); return true ; } template < typename T >void * threadpool< T >::worker ( void * arg ){ threadpool* pool = ( threadpool* )arg; pool->run (); return pool; } template < typename T >void threadpool< T >::run () { while (!m_stop) { m_queuestat.wait (); m_queuelocker.lock (); if ( m_workqueue.empty () ) { m_queuelocker.unlock (); continue ; } T* request = m_workqueue.front (); m_workqueue.pop_front (); m_queuelocker.unlock (); if ( !request ) { continue ; } request->process (); } } #endif