获取内容资料
综合学习

数据结构与算法网易云课堂

类模板是模板的定义,不是一个实实在在的类,定义中用到通用类型参数

模板类是实实在在的类定义。是类模板的实例化。类定义中参数被实际类型所代替

课时37STL基本概念

数据结构与算法网易云课堂

向量(vector)属于序列式容器,用于容纳不定长线行序列,提供对序列的快速随机访问(也称直接访问)

向量是动态结构,模拟动态数组,它的大小不固定,可以在程序运行时增加或减少

vector的元素可以是任意类型T,但必须具有赋值和拷贝能力,具有public的拷贝构造函数和重载的赋值运算符

课时38vector

vector的大小(size)和容量(capacity)通常是不同的,capacity返回vector实际能容纳的元素数量。如果超过这个数量需要重新配置内部存储器

课时40排序算法

STL中的排序算法

sort(num.begin, num.end);是算法(algorithm)库中的排序算法

sort模板有两种

第一种模板,sort重排[first, last]之间的元素,产生一个按operate 排列的序列。sort将序列中的元素以升序方式排序

第二种模板和前一个的行为相似,不过它用sort代替了operate (x, y)

template class Ranlt void sort(Ranlt first, Ranlt last);template class Ranlt, class Pred void sort(Ranlt first, Ranlt last, Pred pr);

示例:使用sort进行排序

#include iostream #include algorithm #include string #include vector class ID{public:ID :name(""), score(0)ID(std::string n, int s) :name(n), score(s)std::string name;int score;};bool operator==(const ID& x, const ID& y)//从小到大需要用到{return (x.name == y.name) && (x.score == y.score);}bool operator (const ID& x, const ID& y)//从小到大需要用到{return x.score y.score;}bool compare(const ID& x, const ID& y)//从大到小需要用到{return x.score y.score;}int main{std::vector ID ids;std::vector ID ::iterator iter;ids.push_back(ID("Tome", 5));ids.push_back(ID("John", 1));ids.push_back(ID("Alex", 2));for (iter = ids.begin; iter != ids.end; ++iter){std::cout (*iter).name " " (*iter).score std::endl;}std::cout "after sort" std::endl;sort(ids.begin, ids.end);//从小到大sort(ids.begin, ids.end, compare);//从大到小,需要用到compare函数for (iter = ids.begin; iter != ids.end; ++iter){std::cout (*iter).name " " (*iter).score std::endl;}system("pause");return 0;}

课时42map

集合set与映射map是两种主要的非线性容器类

内部实现一般为平衡二叉树(balanced binary tree)

map是STL的一个关联容器,它提供一对一的数据处理能力

其中第一个可以称为关键字,每个关键字只能在map中出现一次

第二个可能称为该关键字的值

map的构造

map int, string mapStudent;

map数据的插入

第一种:用insert函数插入pair数据

std::map int, std::string mapStudent;mapStudent.insert(pair int, std::string (1, "student_one"));

第二种:用insert函数插入value_type数据

std::map int, std::string mapStudent;mapStudent.insert(map int, std::string ::value_type(1, "student_one"));

map的大小

在网map里面插入了数据,我们怎么知道当前已经插入了多少数据呢,可以用size函数,用法如下:

int nSize = mapStudent.size;

数据的遍历

std::map int, std::string ::reverse_iterator iter;for (iter = mapStudent.rbegin; iter != mapStudent.rend; iter++)

课时43案例讲解–智能指针

案例讲解

智能指针的使用

案例介绍

使用类模板来管理指针

案例设计

创建模板类管理指针。实现资源的管理

#include iostream #define TRACE printfclass RefCount{public:RefCount{crefs = 0;}virtual ~RefCountvoid upcount{++crefs;TRACE("up to %d\n", crefs);}void downcount{if (–crefs == 0){delete this;}else{TRACE("up to %d\n", crefs);}}private:int crefs;};class Sample :public RefCount{public:Sample{

Similar Posts

发表评论

邮箱地址不会被公开。 必填项已用*标注