2.8学习

1、map和set底层都是红黑树,对于平衡二叉树和红黑树而言
平衡二叉树和红黑数都是防止出现"树一直添加左孩子或有右孩子变成链表的情况",在插入时可以进行左旋右旋变的更加均衡,二者中平衡二叉树的查找效率最高(因为左右子树的高度差距不超过1),但是插入效率较低(要不断左右旋),而对于红黑树,最长的路径最大是最短路径的2倍(一定程度上树的高度就变高了),所以在查找效率上较低,但是插入效率要比平衡二叉树高
set不允许值重复,而且只读,不能修改,除非删除重新添加
2、流迭代器istream_iterator和ostream_iterator,可以把写入的数据储存到容器中

点击查看代码
istream_iterator<int>beg(cin);
	vector<int>words;
	istream_iterator<int>end;
	while (beg != end)
	{
		words.push_back(*beg++);
	}
	sort(words.begin(), words.end());
	ostream_iterator<int>out_iterator(cout," ");
	copy(words.begin(), words.end(), out_iterator);
	cout << endl;
	unique_copy(words.begin(), words.end(), out_iterator);//把重复的去掉
这里有3个文件,把其中一个文件的信息读取出来,然后按照奇偶分别把数据存放到对应的文件中,istream_iterator可以传入ifstream,ostream可以传入ofstream
点击查看代码
ifstream fst("test.txt");
	if (!fst)
	{
		cout << "test打开失败" << endl;
		return 1;
	}
	ofstream out1("out1.txt");
	if (!out1)
	{
		cout << "out1打开失败" << endl;
		return 1;
	}
	ofstream out2("out2.txt");
	if (!out2)
	{
		cout << "out2打开失败" << endl;
		return 1;
	}
	istream_iterator<int>read_is(fst);
	istream_iterator<int>eof;//结尾标志
	ostream_iterator<int>out_1(out1," ");
	ostream_iterator<int>out_2(out2,"\n");
	//读取
	while (read_is != eof)
	{
		if ((*read_is % 2) != 0)//奇
		{
			*out_1++ = *read_is;
		}
		else
		{
			*out_2++ = *read_is;
		}
		read_is++;
	}

3、vector容器的rbegin()指向末尾元素位置,rend()指向首元素之前位置,遍历时仍然是++,进行反向遍历,可以用反向迭代器反向查找数据
比如查找List中最后一个1的位置(返回的迭代器应该++才指向正确的位置),注意反向迭代器要通过base()转化为正常迭代器

点击查看代码
list<int>data = { 1,2,3,4,33,99,1,43,103,1,90 };
	auto position = find(data.rbegin(), data.rend(), 1);//指向1的后一个位置
	position++;
	int true_position = 0;
	for (auto i = data.begin(); i != position.base(); i++, true_position++){}
	cout << true_position;
posted @ 2026-02-09 00:40  dd_l  阅读(1)  评论(0)    收藏  举报