essential c++阅读笔记(1)

学习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提供的容器可以使我们十分的方便完成很多功能,而不用自己去实现。真是“谁用谁知道”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值