栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

STL算法库(2)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

STL算法库(2)

排序算法和拷贝替换的运用
//排序算法
//sort, random_shuffle
#include 
#include 
#include 
#include 
class Myprint
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
void test5()
{
	vector v;
	v.push_back(10);
	v.push_back(100);
	v.push_back(30);
	v.push_back(40);
	//没有排序前打印数据
	for_each(v.begin(), v.end(), Myprint());
	cout << endl;
	//排序
	sort(v.begin(), v.end(), less());
	//排序后打印
	for_each(v.begin(), v.end(), Myprint());
	cout << endl;
	//洗牌
	random_shuffle(v.begin(), v.end());
	for_each(v.begin(), v.end(), Myprint());
}


//拷贝和替换
//copy, replace, replace_if, swap
class MyPrint
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
class Less100
{
public:
	bool operator()(int val)
	{
		return val < 100;
	}
};
void test6()
{
	vector v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i + 10);
	}
	vector vtarget;
	vtarget.resize(v.size());
	copy(v.begin(), v.begin() + 5, vtarget.begin());
	for_each(vtarget.begin(), vtarget.end(), MyPrint());
	cout << endl;
	replace(vtarget.begin(), vtarget.end(), 0, 100);				//将0替换成100
	for_each(vtarget.begin(), vtarget.end(), MyPrint());
	cout << endl;
	replace_if(vtarget.begin(), vtarget.end(), Less100(), 2000);				//Less100()谓词,replace_if条件替换,将小于100的原元素替换成2000
	for_each(vtarget.begin(), vtarget.end(), MyPrint());
	cout << endl;
}


int main()
{
	
	//srand((unsigned int)time(NULL));
	//test5();
	test6();

	system("pause");
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1036151.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号