EssentialC++ 以template进行编程

2024-02-29 23:48

本文主要是介绍EssentialC++ 以template进行编程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这一章通过讲解二叉树的template的实现过程,来讲解template的语法,以及一些需要注意的地方。

首先了解一下二叉树的一些基本操作,二叉树支持插入,删除,遍历的操作。第一个安插至空白树的值,会成为此树的根节点。接下来的每个节点按特定的规则插入。如果小于根节点,就被置于左侧指数,大于根节点就被置于右子树。string类型按照字典排序。如下图

遍历又分前序遍历,中序遍历,后序遍历。

按照上图,前序遍历结果: Piglet,Ek,Chris,Kanga,Roo,Pooh,Trigger. 

中序遍历结果:Chris Ek Kanga Piglet   Pooh Roo Trigger

后序遍历结果:Chris Kanga Ek Pooh Trigger Roo Piglet

下面先实现一个节点类型BTnode。如果不实现泛型,


class string_node {
public:private:string _val;   //节点的值int _cnt;      //节点计数string_node *_lchild;    //左节点string_node *_rchild;    //右节点};

如果要实现存储int类型的节点则又要定义一个int_node类。这显然太麻烦。我们可以定义一个支持泛型的节点。

template<typename valType>
class BTnode {friend class BinaryTree<valType>;    //把二叉树类型BinaryTree声明为友元类,这样BinaryTree就可以访问BTnode的私有成员 _val,_cnt,_lchild,_rchild等
public:BTnode(){}BTnode(const valType &val);void insert_value(const valType& elem);void remove_value( const valType &val, BTnode *& prev);static void lchild_leaf( BTnode *leaf, BTnode *subtree);
private:valType _val;int     _cnt;BTnode *_lchild;BTnode *_rchild;
};

为了通过class template产生实体类,我们必须在class tempalte名称之后,紧接一个尖括号,其内放置一个实际类。例如:BTnode<int> 则将valType绑定至int, BTnode<string>则讲valType绑定至string。这样我们就实现了泛型。没有必要再为

每个类型都定义一个节点类型了。什么情况下我们需要 模板参数列表(template parameter list)去修饰 模板类(class template)呢。 一般的规则是,在class template 以及其members的定义式中,不需要之外。其他的场合都需要以parameter list 加以修饰。如:

template<typename elemType>
class BinaryTree {
public:
...
private:BTnode<elemType> *_root;
};
下面给出BTnode完整的定义:

template<typename Type>
class BinaryTree;template<typename valType>
class BTnode {friend class BinaryTree<valType>;
public:BTnode(){}BTnode(const valType &val);void insert_value(const valType& elem);void remove_value( const valType &val, BTnode *& prev);static void lchild_leaf( BTnode *leaf, BTnode *subtree);
private:valType _val;int     _cnt;BTnode *_lchild;BTnode *_rchild;
};template<typename valType>
BTnode<valType>::BTnode(const valType &val): _val(val)
{_cnt = 1;_lchild = _rchild = 0;
}template<typename valType>
void BTnode<valType>::insert_value(const valType &val) {if ( this->_val == val) {this->_cnt++;         return ;}if(this->_val > val ) {if(!this->_lchild)this->_lchild = new BTnode<valType>(val);elsethis->_lchild->insert_value(val);} else {if(!this->_rchild)this->_rchild = new BTnode<valType>(val);elsethis->_rchild->insert_value(val);}}template<typename valType>
void BTnode<valType>::remove_value( const valType &val, BTnode *& prev) {   //找到相应的值,删除该节点。prev是起始的节点。 这里需要修改BTnode *指针本身,所以我们定义为 BTnode *& previf( val < _val ) {if ( !_lchild)return;else_lchild->remove_value(val, _lchild);}else if ( val > _val) {if( !_rchild)return;else_rchild->remove_value(val,_rchild);}else {if (_rchild) {prev = _rchild;if(_lchild)if( !prev->_lchild)prev->_lchild = _lchild;elseBTnode<valType>::lchild_leaf(_lchild,prev->_lchild);}elseprev = _lchild;delete this;}}template<typename valType>
inline void BTnode<valType>::lchild_leaf( BTnode *leaf, BTnode *subtree) {
//使leaf成为subtree的左子树的叶子节点while (subtree->_lchild)subtree = subtree->_lchild;subtree->_lchild = leaf;
}

template<typename valType>
BTnode<valType>::BTnode(const valType &val): _val(val)
{_cnt = 1;_lchild = _rchild = 0;
}
为什么这里第二次出现BTnode的时候不需要<valType>去修饰了呢,因为在class scope运算符出现之后 BTnode<valType>::,其后所有东西被视为位于class定义域内:还记得上面所说的规则吗在class template 以及其members的定义式中,不需要之外。其他的场合都需要以parameter list 加以修饰。

BTnode<valType>::  //在class定义域之外。

BTnode()    //在class定义域之内。

关于函数参数的规则是,若是非基本类型,则使用传址的方式(by reference)传递 ,如果这个参数确认了,在函数内是只读的则加上const 修饰词。如:

insert_value(const valType &val)

下面给出BinaryTree的模板实现:

template<typename elemType>
class BinaryTree {
public:BinaryTree();BinaryTree(const BinaryTree&);~BinaryTree();BinaryTree& operator= (const BinaryTree&);void insert( const elemType &);bool empty() { return _root == 0;}void remove(const elemType &elem);void remove_root();void clear() { if(_root) { clear(_root); _root = 0;}}void preorder();void preorder(BTnode<elemType> *node, ostream &os = cout);static ostream & display_val( elemType &node,ostream &os = cout);void pre_recursion(BTnode<elemType> *node);BTnode<elemType>* get_root() { return _root;}
private:BTnode<elemType> *_root;void clear(BTnode<elemType> *node);void copy(BTnode<elemType> *tar, BTnode<elemType> *src);
};template<typename elemType>
inline BinaryTree<elemType>::
BinaryTree() : _root(0) {}template<typename elemType>
inline BinaryTree<elemType>::BinaryTree(const BinaryTree& rhs) {copy(_root,rhs._root);
}template<typename elemType>
void BinaryTree<elemType>::insert( const elemType &elem) {if (!_root)_root = new BTnode<elemType>(elem);_root->insert_value(elem);
}template<typename elemType>
inline BinaryTree<elemType>::~BinaryTree() {clear();
}template<typename elemType>
inline BinaryTree<elemType>&
BinaryTree<elemType>::operator= (const BinaryTree &rhs) {if( ! this = &rhs) {clear();copy(_root,rhs._root);}return *this;
}template<typename elemType>
inline void BinaryTree<elemType>::remove( const elemType &elem) {if(_root) {if( _root->_val == elem)remove_root();else_root->remove_value(elem, _root);}
}template<typename elemType>
void BinaryTree<elemType>::
remove_root() {if (!_root) return;BTnode<elemType> *tmp = _root;if( !_root->_rchild) {_root = _root->_rchild;if(tmp->_lchild) {if(!_root->_lchild)//没有任何子树则直接接上_root->_lchild = tmp->_lchild;elseBTnode<elemType>::lchild_leaf(tmp->_lchild,_root->_lchild);}}else_root = _root->_lchild;delete tmp;
}
//清除所有节点
template<typename elemType>
void BinaryTree<elemType>::clear(BTnode<elemType> *node) {if(node) {clear(node->_lchild);clear(node->_rchild);delete node;}
}template<typename elemType>
void BinaryTree<elemType>::preorder() {pre_recursion(_root);
}//递归的前序遍历
template<typename elemType>
void BinaryTree<elemType>::preorder(BTnode<elemType> *node, ostream &os) {if(node) {display_val(node->_val,os);preorder(node->_lchild,os);preorder(node->_rchild,os);}
}template<typename elemType>
ostream & BinaryTree<elemType>::display_val(elemType &node , ostream &os) {os << node << ' ';return os;
}//非递归实现前序遍历
template<typename elemType>
void BinaryTree<elemType>::pre_recursion (BTnode<elemType> *node) {stack<BTnode<elemType>*> s;   //使用先进后出栈s.push(node);while(!s.empty()) {BTnode<elemType>* tmp = s.top();s.pop();BinaryTree<elemType>::display_val(tmp->_val,std::cout);if(tmp->_rchild)s.push(tmp->_rchild);    //右节点先进栈 后出,后遍历if(tmp->_lchild)s.push(tmp->_lchild);    //左节点后进栈,先出,先遍历}
}

测试:

int main()
{BinaryTree<string> bt;bt.insert("abc");bt.insert("agcb");bt.insert("kfgd");bt.insert("how are you");bt.preorder();//bt.remove("abc");//bt.preorder();bt.remove("kfgd");bt.preorder();return 0;
}
本章不仅让我了解泛型编程,模板类是怎么一回事,template的语法。而且还让我重温了一次二叉排序树 这个数据结构。


参考文献:

《Eseential C++》


这篇关于EssentialC++ 以template进行编程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/760500

相关文章

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么

一文解密Python进行监控进程的黑科技

《一文解密Python进行监控进程的黑科技》在计算机系统管理和应用性能优化中,监控进程的CPU、内存和IO使用率是非常重要的任务,下面我们就来讲讲如何Python写一个简单使用的监控进程的工具吧... 目录准备工作监控CPU使用率监控内存使用率监控IO使用率小工具代码整合在计算机系统管理和应用性能优化中,监

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

MySQL进行数据库审计的详细步骤和示例代码

《MySQL进行数据库审计的详细步骤和示例代码》数据库审计通过触发器、内置功能及第三方工具记录和监控数据库活动,确保安全、完整与合规,Java代码实现自动化日志记录,整合分析系统提升监控效率,本文给大... 目录一、数据库审计的基本概念二、使用触发器进行数据库审计1. 创建审计表2. 创建触发器三、Java

C++中全局变量和局部变量的区别

《C++中全局变量和局部变量的区别》本文主要介绍了C++中全局变量和局部变量的区别,全局变量和局部变量在作用域和生命周期上有显著的区别,下面就来介绍一下,感兴趣的可以了解一下... 目录一、全局变量定义生命周期存储位置代码示例输出二、局部变量定义生命周期存储位置代码示例输出三、全局变量和局部变量的区别作用域

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

MySQL深分页进行性能优化的常见方法

《MySQL深分页进行性能优化的常见方法》在Web应用中,分页查询是数据库操作中的常见需求,然而,在面对大型数据集时,深分页(deeppagination)却成为了性能优化的一个挑战,在本文中,我们将... 目录引言:深分页,真的只是“翻页慢”那么简单吗?一、背景介绍二、深分页的性能问题三、业务场景分析四、