2.5学习

1、function封装lambda表达式,本来lambda表达式是个匿名函数,通过function可以给lambda赋名
<int(int)>表示返回值为int,传入的参数为int,且这里的&不能改为=,因为第一步fatoral是空的,当执行到fatoral=[&fatoral](int n){}时才会给fatoral赋值,但是这时lambda表达式已经通过值传入=将空的fatoral传入了,所以会执行错误,必须用&引用传入

点击查看代码
function<int(int)>fatoral;
	fatoral=[&fatoral](int n)
	{
		return (n <= 1) ? 1 : n * fatoral(n - 1);
	};
2、双向链表list和双向队列deque,list添加删除效率高,但是检索效率不高,deque本质是多个内存连续的数组和一个指向这些数组的指针数组,由于指针的存在,可以随时访问这些数组,但是如果是在中间插入数据就会比较困难

3、bind绑定函数,可以将函数的参数列表中一个参数固定为一个值
比如count_if算法,本来要求只传入一个一元谓词,但是is_long是二元的,所以用bind绑定其中一个参数为size,这样就变成了一个一元谓词,但是我感觉还是lambda好用……

点击查看代码
bool is_long(const string&s1, const string::size_type size)
{
	return s1.size() > size;
}
void fun(vector<string>&&vv,vector<int>::size_type size)
{
	int number = count_if(vv.begin(), vv.end(), bind(is_long, placeholders::_1,size));
	//int number = count_if(vv.begin(), vv.end(), [size](const string&temp) {return temp.size() > size; });
	cout << "长度大于" << size << "的数量为" << number;
}

4、流迭代器,istream_iterator,可以将文件流当作容器来遍历,istream_iteratorend默认构造是文件流的末尾

点击查看代码
	ifstream fst("stringTest.txt");
	if (!fst)
	{
		cout << "打开失败" << endl;
		return 1;
	}
	istream_iterator<string>beg(fst);
	vector<string>words;
	istream_iterator<string>end;
	while (beg != end)
	{
		words.push_back(*beg++);
	}

posted @ 2026-02-05 10:58  dd_l  阅读(3)  评论(0)    收藏  举报