STL模版知识汇总

不废话直接上代码,测试过,可运行!

/*****************************
**文件名称:Vector_Test.cpp 
**功能简介:STL 模版知识汇总
**创建日期:2018-09-21
**修改日期:
**创建人员:viture_li [email protected]
**文件版本:
*****************************/

#pragma once
#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

//vector模版
template  
void showVector(vector v)
{
	for(vector::iterator it = v.begin();it != v.end();it++)
	{
		cout << *it;
		cout << endl;
	}
	cout << endl;
}

//set模版
template  
void showSet(set s)
{
	for(set::iterator it = s.begin();it != s.end();it++)
	{
		cout << *it;
		cout << endl;
	}
	cout << endl;
}

//list模版
template  
void showList(list s)
{
	for(list::iterator it = s.begin();it != s.end();it++)
	{
		cout << *it;
		cout << endl;
	}
	cout << endl;
}

// map
void showmap(map s)
{
	for(map::iterator it = s.begin();it != s.end();it++)
	{
		cout << it->first << " " << it->second << endl;
	}
	cout << endl;
}


int _tmain(int argc, _TCHAR* argv[])
{
	//模版之vector
	cout << "初始化" << endl;
	string str[] = {"hello","This","is","a","STL_Vector","demo"};
	vector v_str(str,str+6);
	showVector(v_str);

	cout << "复制元素" << endl;
	vector v_str1(v_str);
	showVector(v_str1);

	cout << "重新调整vector容量大小" << endl;
	v_str.resize(3);
	showVector(v_str);

	cout << "访问第一个元素" << endl;
	cout << v_str1.front()< s" << endl;
	int intset[] = {1,4,5,7,8,2,3,6,9,0};
	set s(intset,intset+10);
	showSet(s);

	cout << "新建一个set s_str,自动字典排序" << endl;
	string str_set[] = {"a","f","b","c","d","k"};
	set s_str(str_set,str_set+6);
	showSet(s_str);

	cout << "insert一个已经存在的数" << endl;
	s.insert(9);
	showSet(s);

	cout << "insert一个不存在的string" << endl;
	s_str.insert("e");
	showSet(s_str);

	//模版之list
	cout << "list l 初始化" << endl;
	int a[] = {1,4,5,7,9,100,23,43,56,5};
	list l(a,a+10);
	showList(l);

	cout << "将元素都初始化为9" << endl;
	list nine(l.size(),9);
	showList(nine);

	cout << "自动排序" << endl;
	int aa[] = { 8,5,7,6,1,2,3,4,5,5,6,7,7 };
	list so(aa,aa+10);
	so.sort();
	showList(so);
	
	// 模版之map
	cout << "模版之 map" << endl;
	map m;
	m["medicine"] = 1;
	m["faming"]   = 2;
	m["industry"] = 3;
	m["technology"] = 4;

	string fy("fy");
	m[fy] = 90;

	cout << "打印出map元素" << endl;
	showmap(m);
	cout << "medicine: " << m["medicine"] << endl;
	cout << "error: " << m["error"] << endl;

	cout << "通过关键字来删除" <("fy",90));
	showmap(m);

	cout << "使用 count()来判断是否存在key" << endl;
	if(m.count("fy"))
	{
		cout << "fy is in map !" << endl;
	}
	else
	{
		cout << "fy is't in map !" << endl;
	}

	cout << "清空" << endl;
	m.clear();
	showmap(m);


	system("pause");
	return 0;
}

 

你可能感兴趣的:(C/C++随记小知识)