c++ STL常用算法使用方法

#include <string>
#include <vector>
#include <functional>
#include <iostream>
using namespace std;

void print(vector<int>& list, const string &des)
{
	cout<<"after "<<des.c_str()<<", the list is: "<<endl;
	for(vector<int>::iterator iter = list.begin(); iter != list.end(); ++iter)
	{
		cout<<(*iter)<<" ";
	}
	cout<<endl;
}

void printstr(vector<string>& list, const string &des)
{
	cout<<"after "<<des.c_str()<<", the list is: "<<endl;
	for(vector<string>::iterator iter = list.begin(); iter != list.end(); ++iter)
	{
		cout<<(*iter)<<" ";
	}
	cout<<endl;
}

template<class T>
struct comp:public std::binary_function<T,T,bool>
{
	bool operator()(const T &t1, const T &t2) const
	{
		return t1 > t2;
	}
};

struct conv : public std::unary_function<string, string>
{
	string& operator()(string &str)
	{
		std::transform(str.begin(), str.end(), str.begin(), ::tolower);
		return str;
	}
};

int main()
{
	vector<int> list;
	list.push_back(2324);
	list.push_back(45);
	list.push_back(576);
	list.push_back(768);
	list.push_back(21);
	list.push_back(4);
	list.push_back(1);
	list.push_back(54758);
	list.push_back(123);
	list.push_back(464);
	list.push_back(88);
	print(list, "push back");

	std::sort(list.begin(), list.end());
	print(list, "normal sort");

	vector<int>::iterator iter = lower_bound(list.begin(), list.end(), 5);
	cout<<"lower find element is 5, value "<<(*iter)<<endl;

	iter = upper_bound(list.begin(), list.end(), 5);
	cout<<"upper find element is 5, value "<<(*iter)<<endl;
	
	bool ret = std::binary_search(list.begin(), list.end(), 464);
	if(ret)
	{
		cout<<"find 464, value ok."<<endl;
	}

	std::sort(list.begin(), list.end(), comp<int>());
	print(list, "big sort");

	iter = lower_bound(list.begin(), list.end(), 5);
	cout<<"lower find element is 5, value "<<(*iter)<<endl;

	iter = upper_bound(list.begin(), list.end(), 5);
	cout<<"upper find element is 5, value "<<(*iter)<<endl;

	ret = std::binary_search(list.begin(), list.end(), 88, comp<int>());
	if(ret)
	{
		cout<<"find 88, value ok."<<endl;
	}

	list.insert(std::upper_bound(list.begin(), list.end(), 55, comp<int>()), 55);
	print(list, "upper bound insert");

	list.insert(std::lower_bound(list.begin(), list.end(), 77, comp<int>()), 77);
	print(list, "lower bound insert");

	iter = std::search(list.begin(), list.end(), list.begin() + 4, list.begin() + 6);
	if(iter != list.end())
	{
		cout<<"search seq pos is "<<(*iter)<<endl;
	}

	vector<string> strList;
	strList.push_back("AAAA");
	strList.push_back("BBBB");
	strList.push_back("CCCC");
	printstr(strList,"str list");

	std::transform(strList.begin(), strList.end(), strList.begin(), conv());
	printstr(strList, "transform");

	// sort之后才能执行unique

	return 0;
}

  上面的使用主要起到抛砖引玉的作用,可根据实际情况借鉴使用方法使用其它算法。

 

posted on 2015-07-29 10:02  霏霏暮雨  阅读(462)  评论(0编辑  收藏  举报

导航