学习c++的同学很多老师和同学都推荐《c++ primer》这本书,但是这本书有1千多页,知识点特别多,而且不能使初学者很快的上手,在这里我比较推荐《essential c++》这本书。读者使用c++有1年多,这次阅读,收获颇多,在此做笔记重新温习一下。
1,文件的读写
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile("6.txt", ios_base::app);
if(!outfile)
{
cerr << "open file 6.txt error" << endl;
exit(0);
}
outfile << "lemon " << "10 " << "12" << endl;
string name;
int nt;
int nc;
ifstream infile("6.txt");
infile >> name;
cout << name << endl;
return 0;
}
此处展示了ifstream和ofstream的使用,如果想同时可读可写,可以用fstream,详细使用请参考具体资料。
2,引用的使用
引用相当于变量的别名,对于引用的操作将全部作用于变量本身。引用比较有用的地方就是函数中的传参问题,在学习函数传参时,经常遇到的一个问题就是传值还是传址,采用引用就相当于传址,而且写起来也十分的方便,不像指针那么的复杂。
#include <iostream>
using namespace std;
void swap(int &x, int &y)
{
int temp = x;
x= y;
y = temp;
return ;
}
int main()
{
int x = 1, y = 2;
cout << "before swap, x = " << x << " , y = " << y << " ." << endl;
swap(x, y);
cout << "after swap, x = " << x << " , y = " << y << " ." << endl;
return 0;
}
利用引用,就可以实现了swap功能。
3,所有容器的共通操作
(1)equality(==)和inequality(!=)运算符,返回true或false。
(2)assignment(=)运算符,将某个容器复制给另一个容器。
(3)empty()会在容器无任何元素的时候返回true,否则返回false。
(4)size()传用容器内当前含有的元素数目。
4,使用泛型算法
find(),cout(), sort()的使用,本人经常使用的一个泛型算法是sort(),用来排序,感觉非常方便。
5,Function Objects
A Function Object, or Functor (the two terms are synonymous)is simply any object that can be called as if it is a function.An ordinary function is a function object, and so is a function pointer;more generally, so is an object of a class that defines operator().
头文件#include <functional>
使用sort(vec.begin(), vec.end(), greater<int>());
6,使用Map,Set,vector,list等容器
使用这些STL提供的容器可以使我们十分的方便完成很多功能,而不用自己去实现。真是“谁用谁知道”。