C++ STL容器篇

STL的容器,通过类模板技术实现数据类型和容器模型的分离,STL的迭代器技术实现了遍历容器的统一方法,也为STL的算法提供了统一性奠定了基础,STL的算法通过函数对象实现了自定义数据类型的算法运算,所以说STL的算法也提供了统一性.

核心思想:其实函数对象本质就是回调函数,回调函数的思想就是任务的编写者和任务的调用者,有效解耦合函数指针作函数参数.

二元函数和二元谓词 示例代码

#include
using namespace std;
#include"vector"
#include"map"
#include"string"
#include"list"
#include"set"
#include"functional"
//函数对象和谓词
template

class SumAdd
{
public:
	T operator()(T t1, T t2)
	{
		return t1 + t2;
	}

};


void main11()
{
	vector v1, v2;
	vector  v3;
	v1.push_back(1);
	v1.push_back(3);
	v1.push_back(5);

	v2.push_back(2);
	v2.push_back(4);
	v2.push_back(6);
	v3.reserve(10);
	transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), SumAdd());
	for (vector::iterator it = v3.begin(); it != v3.end(); it++);
	{
		cout << *it << endl;
	}
}
//二元谓词
bool MyCompare(const int &a, const int &b)
{
	return a < b;///从小到大
}
void main22()
{
	vector v1(10);
	for (int i = 0; i < 10; i++)
	{
		int tmp = rand() % 100;
		v[i] = tmp;
	}
	for (vector::iterator it = v1.begin(); it != v1.end(); it++);//用迭代器的方式打印出来
	{
		cout << *it << endl;
	}
	cout << endl;
	for_each(v1.begin(), v1.end(), FuncShowElemt2);
	cout << endl;
	sort(v1.begin(), v1.end(), MyCompare);
	for_each(v1.begin(), v1.end(), FuncShowElemt2);
	cout << endl;
}
struct CompareNoCase
{
	bool operator()(const string &str1, const string &str2)
	{
		string str1_;
		str1_resize(str1.size());
		transform(str1.begin(), str1.end(), str1_.begin(), tolower);//预定义函数对象
			
		return(str1 < str2);//从小到大排序
	}
};
void main33()
{
	set set1;
	set1.insert("bbb");
	set1.insert("aaa");
	set1.insert("ccc");
	//set::iterator it = set1.find("aaa");//find函数默认区分大小写
	set::iterator it=set1.find("aAa");//find函数默认区分大小写
	if (it == set1.end())
	{
		cout << " no nothing" << endl;
	}
	else
	{
		cout << "nothing" << endl;
	}
	setset2;
	set2.insert("bbb");
	set2.insert("aaa");
	set2.insert("ccc");
	set::iterator it2 = set2.find("aAa");
	if (it2 == set2.end())
	{
		cout << " no nothing" << endl;
	}
	else
	{
		cout << "不区分大写小写nothing" << endl;
	}
}
void main()
{
	main11();
	main22();//二元函数和二元谓词
	main33();//二元谓词在set集合中的应用


	cout << "hello..." << endl;
	system("pause");
	return;
}
展开阅读全文

页面更新:2024-05-23

标签:容器   谓词   编写者   遍历   大小写   示例   指针   从小到大   算法   数据类型   函数   本质   对象   思想   技术   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top