STL简介和实例代码

本文介绍了STL的基础知识,包括STL的三大主要组件,并通过实例代码展示了如何使用容器、算法和迭代器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0x00 什么是STL

STL是Standard Template Library的简称,对数据结构的再一次封装。

0x01 stl常用的三大组件

1.1 容器
序列容器
关联式容器


1.2 算法
质变算法
非质变算法


1.3 迭代器
输入迭代器
输出迭代器
向前迭代器
双向迭代器
随机访问迭代器


0x02  实例代码

以实例代码对容器、算法、迭代器进行简单的使用

//main.cpp

// StlPro.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "MyVecFunc.h"


int main(int argc, char* argv[])
{
	bool execute_status = false;
	
	vector<int> myvec;
	
	//初始化vector
	//容器的初始化
	execute_status = InitVecFunc(&myvec);
	if (false == execute_status)
	{
		cout << "main->InitVecFunc 执行失败!" << endl;
		exit(1);
	}
	
	//迭代器的使用
	execute_status = ShowVecDataFunc(&myvec);
	if (false == execute_status)
	{
		cout << "main->ShowVecDataFunc" << endl;
		exit(1);
	}

	//算法的使用
	execute_status = SortVecFunc(&myvec);
	if (false == execute_status)
	{
		cout << "main->SortVecFunc" << endl;
		exit(1);
	}
    return 0;
}



//MyVecFunc.h

#ifndef __MY_VEC_FUNC_H__
#define __MY_VEC_FUNC_H__

#define FUNC_SUCCESS true
#define FUNC_FAILT	 false

/********************
初始化vector
*/
bool InitVecFunc(vector<int>* pvec);

/********************
显示vector 数据
*/
bool ShowVecDataFunc(vector<int>* pvec);

/********************
对vectore进行排序
*/
bool SortVecFunc(vector<int>* pvec);
#endif


  //MyVecFunc.cpp

#include "stdafx.h"
#include "MyVecFunc.h"


bool InitVecFunc(vector<int>* pvec)
{
	if (NULL == pvec)
	{
		cout << "InitVecFunc 形参有问题" << endl;
		return FUNC_FAILT;
	}

	srand((unsigned)time(NULL));
	for (int i = 0; i < 10; i++)
	{
		pvec->push_back(rand()+3);
	}

	return FUNC_SUCCESS;
}

/********************
显示vector 数据
*/
bool ShowVecDataFunc(vector<int>* pvec)
{
	if (NULL == pvec)
	{
		cout << "ShowVecDataFunc 参数有问题" << endl;
		return FUNC_FAILT;
	}

	//使用迭代器将数据进行输出
	vector<int>::iterator vec_it;
	//
	cout << "迭代器输出:" << endl;
	for (vec_it = pvec->begin(); 
		 vec_it != pvec->end(); 
		 ++ vec_it)
	{
		cout << *vec_it << " " ;
	}
	
	cout << endl;
	return FUNC_SUCCESS;
}

/********************
对vectore进行排序
*/
bool SortVecFunc(vector<int>* pvec)
{
	bool exe_status = false;
	
	if (NULL == pvec)
	{
		cout << "SortVecFunc" << endl;
		return FUNC_FAILT;
	}

	sort(pvec->begin(), pvec->end());
	//将排序后的数据输出
	exe_status = ShowVecDataFunc(pvec);
	if (FUNC_FAILT == exe_status)
	{
		cout << "SortVecFunc->ShowVecDataFunc" << endl;
		return FUNC_FAILT;
	}

	return FUNC_SUCCESS;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值