C++学习笔记【转】

Debug : 在单独运行时,往往需要编译器提供一些库文件

Release : 可以在没有安装visual c++的computer上正常运行

 

常规设置

1)
在共享DLL中使用MFC : 表示把程序中用到的MFC类库作为动态链接库,这样编译生成器的程序比较小,但是在运行的时候,需要操作系统提供额外的动态库支持。

2)
在静态库中使用MFC : 表示把用到的MFC类的内容作为静态库加到程序中,这样编译产生的程序可以在任何Windwos环境下运行,但是程序的体积比较大。

3)
使用标准Windows库 : 表示不适用MFC类库,仅使用标准的Windows类库。


#define and const
宏的使用是在预处理的时候进行五条件的替换,并没有明确指定这个常量的数据类型、所以带来便利的同时也容易带来问题。
所以出现了const


枚举的使用---------------------------------

  1. enum Weekday  
  2. {  
  3.     mon,  
  4.     tue,  
  5.     wed,  
  6.     thu,  
  7.     fri,  
  8.     sat,  
  9.     sun  
  10. };  
enum Weekday
{
	mon,
	tue,
	wed,
	thu,
	fri,
	sat,
	sun
};


枚举默认的值是0,如果不想用默认,可以直接赋值
枚举定义之后,不能再修改其中某个元素的值


使用位操作符---------------------------------------------------

 
  1.     cout << "use transpose operator :" << endl;  
  2.     int iValue = 1;  
  3. //  iValue = iValue * 4;  
  4.     iValue = iValue << 34; // 34 % 32 = 2左移 因为超过了int的大小空间  
  5.     cout << "iValue value is : " << iValue << endl;  
	cout << "use transpose operator :" << endl;
	int iValue = 1;
//	iValue = iValue * 4;
	iValue = iValue << 34; // 34 % 32 = 2左移 因为超过了int的大小空间
	cout << "iValue value is : " << iValue << endl;


 

内联函数 :
可以更形象地称为内嵌函数,它是C++对函数的一种特殊修饰。当编译器编译程序时,如果发现某段代码在调用一个内联函数,它就不再去调用该函数,而是将该函数的代码整段插入当前函数调用的位置。这样就省去了函数调用的过程,提高了代码的执行效率。关键字inline


函数重载 :
1)函数重载的意义在于可以根据输入参数的类型或者个数,自动地在多个重载函数中查找与之匹配的重载函数,从而只能地决定采用哪个函数版本。
2)只有相互之间的参数类型或者个数不同,才可以构成合法的重载函数


函数的声明----也称为函数的接口
1)试一试在纯c中使用接口------------------------------------------------
2)尽量在函数中使用断言assert判断函数的有效性
3)函数的功能要做到单一----如果一个函数需要完成多项任务,最好拆分成多个函数


面向对象的知识 :
1)封装
在传统的结构化程序设计思想中,数据和算法是相互分离的。
在面向对象的程序设计思想中,对象就是封装数据和操作这些数据的算法的逻辑实体,也是现实世界中物体在程序中的反映,使用封装有的时候可以很好的保护对象的私有部分

2)继承
从父亲那里得到技能,自己又可以继续学习。比如我现在就站在前人的基础上学习的c++

3)多态
就是指对象在不同情况下具有不同形式的能力。多态机制使具有不同内部结构的对象可以共享相同的外部接口。比如,给别人一幅画,不一定是你自己画的,也可以直接把你老爸的画送出

想想 : 如何在面向对象程序设计思想上,考虑扩展、复用、可维护问题


new :
在new不成功是,不必去判断指针是否为null,因为new不成功时,系统会自动抛出std::bad_alloc异常,new操作永远不会返回null


拷贝构造函数 :
默认也会有拷贝构造函数,当类中含有指针类型的属性时,以拷贝内存形式出现的默认拷贝构造函数只能复制指针属性的值,而不能复制指针属性所指向的内存,在这个情况下需要自定义类的拷贝函数,完成指针属性等需要页数处理的属性的拷贝工作。

p163 拷贝构造函数

 
  1. namespace Zeng  
  2. {  
  3.     class CTest_A  
  4.     {  
  5.     public:  
  6.         CTest_A( int iValue, char* cName )  
  7.         {  
  8.             this->m_iValue = iValue;  
  9.             this->m_pName = new char[ strlen( cName ) + 1 ];  
  10.             strcpy( m_pName, cName );  
  11.         }  
  12.         // 拷贝构造函数  
  13.         CTest_A( const CTest_A& rCG )  
  14.         {  
  15.             this->m_iValue = rCG.m_iValue;  
  16.             this->m_pName = new char[ strlen( rCG.m_pName ) + 1 ];  
  17.             strcpy( m_pName, rCG.m_pName );  
  18.         }  
  19.         void print()  
  20.         {  
  21.             cout << "CTest_G m_iValue value is : " << this->m_iValue << endl;   
  22.             cout << "CTest_G m_pName value is : " << this->m_pName << endl;   
  23.             cout << "CTest_G m_pName address is : " << *this->m_pName << endl;   
  24.         }  
  25.     public:  
  26.         int m_iValue;  
  27.         char* m_pName;  
  28.     }; // 试试拷贝构造函数  
  29. }  
  30.   
  31. int _tmain(int argc, _TCHAR* argv[])  
  32. {  
  33.     Zeng::CTest_A CA( 10, "Zengraoli" );  
  34.     Zeng::CTest_A CA2( 10, "Zengraoli" );  
  35.     Zeng::CTest_A CA3( CG );  
  36.     cout << "CA print" << endl;  
  37.     CA.print();  
  38.   
  39.     cout << "\n";  
  40.     cout << "CA2 print" << endl;  
  41.     CA2.print();  
  42.   
  43.     cout << "\n";  
  44.     cout << "CA3 print" << endl;  
  45.     CA3.print();  
  46.     cout << "class CTest_A size is : " << sizeof( Zeng::CTest_A ) << endl;  
  47.   
  48.     return 0;  
  49. }  
namespace Zeng
{
	class CTest_A
	{
	public:
		CTest_A( int iValue, char* cName )
		{
			this->m_iValue = iValue;
			this->m_pName = new char[ strlen( cName ) + 1 ];
			strcpy( m_pName, cName );
		}
		// 拷贝构造函数
		CTest_A( const CTest_A& rCG )
		{
			this->m_iValue = rCG.m_iValue;
			this->m_pName = new char[ strlen( rCG.m_pName ) + 1 ];
			strcpy( m_pName, rCG.m_pName );
		}
		void print()
		{
			cout << "CTest_G m_iValue value is : " << this->m_iValue << endl; 
			cout << "CTest_G m_pName value is : " << this->m_pName << endl; 
			cout << "CTest_G m_pName address is : " << *this->m_pName << endl; 
		}
	public:
		int m_iValue;
		char* m_pName;
	}; // 试试拷贝构造函数
}

int _tmain(int argc, _TCHAR* argv[])
{
	Zeng::CTest_A CA( 10, "Zengraoli" );
	Zeng::CTest_A CA2( 10, "Zengraoli" );
	Zeng::CTest_A CA3( CG );
	cout << "CA print" << endl;
	CA.print();

	cout << "\n";
	cout << "CA2 print" << endl;
	CA2.print();

	cout << "\n";
	cout << "CA3 print" << endl;
	CA3.print();
	cout << "class CTest_A size is : " << sizeof( Zeng::CTest_A ) << endl;

	return 0;
}


 

P166 操作符重载
函数重载和操作符重载-------------------------------------

 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4.   
  5. namespace Zeng  
  6. {  
  7.     class CTest_A  
  8.     {  
  9.     public:  
  10.         CTest_A()  
  11.         {  
  12.         }  
  13.         void print()  
  14.         {  
  15.             cout << "this is CTest_A print()" << endl;  
  16.         }  
  17.     }; // 占1个字节的大小  
  18.   
  19.     class CTest_B : virtual CTest_A  
  20.     {  
  21.     public:  
  22.         CTest_B( int iValue ) : m_iValue( iValue )  
  23.         {  
  24.         }  
  25.         void print()  
  26.         {  
  27.             cout << "m_iValue value is : " << m_iValue << endl;  
  28.         }  
  29.     private:  
  30.         int m_iValue;  
  31.     }; // 占8个字节的大小  
  32.   
  33.     class CTest_C : virtual CTest_A  
  34.     {  
  35.     public:  
  36.         CTest_C()  
  37.         {  
  38.         }  
  39.     }; // 占4个字节的大小  
  40.   
  41.     class CTest_D : virtual CTest_B  
  42.     {  
  43.     public:  
  44.         CTest_D( int iValue ) : CTest_B( iValue )  
  45.         {  
  46.             this->m_iValue = iValue + 89;  
  47.         }  
  48.         void print()  
  49.         {  
  50.             cout << "m_iValue value is : " << this->m_iValue << endl;  
  51.         }  
  52.     private:  
  53.         int m_iValue;  
  54.     }; // 占16个字节的大小  
  55.   
  56.     class CTest_E : public CTest_A  
  57.     {  
  58.     public:  
  59.         CTest_E( int iValue )  
  60.         {  
  61.             this->m_iValue = iValue + 89;  
  62.         }  
  63.         void print()  
  64.         {  
  65.             cout << "this is CTest_E not parameter's print()" << endl;  
  66.         }  
  67.         void print( int iValue )  
  68.         {  
  69.             cout << "this is CTest_E has parameter's print()" << endl;  
  70.         }  
  71. /* 
  72.         int print( int iValue ) 
  73.         { 
  74.             cout << "this is CTest_E has parameter's print()" << endl; 
  75.             return 0; 
  76.         } // c++可以忽略函数的返回值,所以只能靠参数不同来进行函数重载 
  77. */  
  78.     private:  
  79.         int m_iValue;  
  80.     }; // 试试函数重载  
  81.   
  82.     class CTest_F  
  83.     {  
  84.     public:  
  85.         CTest_F( int iValue )  
  86.         {  
  87.             this->m_iValue = iValue;  
  88.         }  
  89.         void print()  
  90.         {  
  91.             cout << "CTest_F m_iValue value is : " << this->m_iValue << endl;   
  92.         }  
  93.         const CTest_F& operator+ ( const CTest_F& rCF )  
  94.         {  
  95.             this->m_iValue += rCF.m_iValue;  
  96.             return *this;  
  97.         }  
  98.         const CTest_F& operator= ( const CTest_F& rCF )  
  99.         {  
  100.             this->m_iValue = rCF.m_iValue;  
  101.             return *this;  
  102.         }  
  103.     public:  
  104.         int m_iValue;  
  105.     }; // 试试操作符重载  
  106. }  
  107.   
  108. int _tmain(int argc, _TCHAR* argv[])  
  109. {  
  110.     Zeng::CTest_A CA;  
  111.     CA.print();  
  112.     cout << "class CTest_A size is : " << sizeof( Zeng::CTest_A ) << endl;  
  113.     cout << "class CTest_B size is : " << sizeof( Zeng::CTest_B ) << endl;  
  114.     cout << "class CTest_C size is : " << sizeof( Zeng::CTest_C ) << endl;  
  115.   
  116.     cout << "\n";  
  117.     Zeng::CTest_D CD( 10 );  
  118.     CD.print();  
  119.     cout << "class CTest_D size is : " << sizeof( Zeng::CTest_D ) << endl;  
  120.   
  121.     cout << "\n";  
  122.     Zeng::CTest_E CE( 10 );  
  123.     CE.print();  
  124.     CE.print(1);  
  125.     cout << "class CTest_E size is : " << sizeof( Zeng::CTest_E ) << endl;  
  126.   
  127.     cout << "\n";  
  128.     Zeng::CTest_F CF( 10 );  
  129.     Zeng::CTest_F CF2( 89 );  
  130.     CF = CF + CF2;  
  131.     cout << "in class CTest_F override add after : " << sizeof( Zeng::CTest_F ) << endl;  
  132.     CF.print();  
  133.     CF = CF2;  
  134.     cout << "in class CTest_F override equal after : " << sizeof( Zeng::CTest_F ) << endl;  
  135.     CF.print();  
  136.     cout << "class CTest_F size is : " << sizeof( Zeng::CTest_F ) << endl;  
  137.   
  138.     return 0;  
  139. }  
#include "stdafx.h"
#include "iostream"
using namespace std;

namespace Zeng
{
	class CTest_A
	{
	public:
		CTest_A()
		{
		}
		void print()
		{
			cout << "this is CTest_A print()" << endl;
		}
	}; // 占1个字节的大小

	class CTest_B : virtual CTest_A
	{
	public:
		CTest_B( int iValue ) : m_iValue( iValue )
		{
		}
		void print()
		{
			cout << "m_iValue value is : " << m_iValue << endl;
		}
	private:
		int m_iValue;
	}; // 占8个字节的大小

	class CTest_C : virtual CTest_A
	{
	public:
		CTest_C()
		{
		}
	}; // 占4个字节的大小

	class CTest_D : virtual CTest_B
	{
	public:
		CTest_D( int iValue ) : CTest_B( iValue )
		{
			this->m_iValue = iValue + 89;
		}
		void print()
		{
			cout << "m_iValue value is : " << this->m_iValue << endl;
		}
	private:
		int m_iValue;
	}; // 占16个字节的大小

	class CTest_E : public CTest_A
	{
	public:
		CTest_E( int iValue )
		{
			this->m_iValue = iValue + 89;
		}
		void print()
		{
			cout << "this is CTest_E not parameter's print()" << endl;
		}
		void print( int iValue )
		{
			cout << "this is CTest_E has parameter's print()" << endl;
		}
/*
		int print( int iValue )
		{
			cout << "this is CTest_E has parameter's print()" << endl;
			return 0;
		} // c++可以忽略函数的返回值,所以只能靠参数不同来进行函数重载
*/
	private:
		int m_iValue;
	}; // 试试函数重载

	class CTest_F
	{
	public:
		CTest_F( int iValue )
		{
			this->m_iValue = iValue;
		}
		void print()
		{
			cout << "CTest_F m_iValue value is : " << this->m_iValue << endl; 
		}
		const CTest_F& operator+ ( const CTest_F& rCF )
		{
			this->m_iValue += rCF.m_iValue;
			return *this;
		}
		const CTest_F& operator= ( const CTest_F& rCF )
		{
			this->m_iValue = rCF.m_iValue;
			return *this;
		}
	public:
		int m_iValue;
	}; // 试试操作符重载
}

int _tmain(int argc, _TCHAR* argv[])
{
	Zeng::CTest_A CA;
	CA.print();
	cout << "class CTest_A size is : " << sizeof( Zeng::CTest_A ) << endl;
	cout << "class CTest_B size is : " << sizeof( Zeng::CTest_B ) << endl;
	cout << "class CTest_C size is : " << sizeof( Zeng::CTest_C ) << endl;

	cout << "\n";
	Zeng::CTest_D CD( 10 );
	CD.print();
	cout << "class CTest_D size is : " << sizeof( Zeng::CTest_D ) << endl;

	cout << "\n";
	Zeng::CTest_E CE( 10 );
	CE.print();
	CE.print(1);
	cout << "class CTest_E size is : " << sizeof( Zeng::CTest_E ) << endl;

	cout << "\n";
	Zeng::CTest_F CF( 10 );
	Zeng::CTest_F CF2( 89 );
	CF = CF + CF2;
	cout << "in class CTest_F override add after : " << sizeof( Zeng::CTest_F ) << endl;
	CF.print();
	CF = CF2;
	cout << "in class CTest_F override equal after : " << sizeof( Zeng::CTest_F ) << endl;
	CF.print();
	cout << "class CTest_F size is : " << sizeof( Zeng::CTest_F ) << endl;

	return 0;
}


 


构造函数私有化的含义---------------------------------------------

 
  1. namespace Rao  
  2. {  
  3.     class CTest  
  4.     {  
  5.     public:  
  6.         static CTest* makeAnObject()  
  7.         {  
  8.              // 程序结束的时候 自动释放  
  9.             static CTest instance;  
  10.             return &instance;  
  11.         }  
  12.         ~CTest()  
  13.         {  
  14.             cout << "CTest Destructor...." << endl;  
  15.         }  
  16.         static int m_nValue;  
  17.     private:  
  18.         CTest()  
  19.         {  
  20.             m_nValue++;  
  21.             cout << "CTest Constructor...." << endl;  
  22.         }  
  23.           
  24.         CTest( const CTest& CopyCTest )  
  25.         {  
  26.             m_nValue++;  
  27.             cout << "CopyCTest Constructor...." << endl;  
  28.         }  
  29.   
  30.         const  CTest& operator= ( const CTest& );  
  31.     };  
  32. }  
  33. main:  
  34.     int Rao::CTest::m_nValue;  
  35.   
  36.     cout << "\n";  
  37.     cout << "use Constructor privatization :" << endl;  
  38.     Rao::CTest* RaoCTest = Rao::CTest::makeAnObject();  
  39.     cout << "m_nValue :" << Rao::CTest::m_nValue << endl;  
  40.     Rao::CTest* RaoCTest2 = Rao::CTest::makeAnObject();  
  41.     cout << "m_nValue :" << Rao::CTest::m_nValue << endl;  
  42.   
  43.     // 调用拷贝构造函数  
  44.     Rao::CTest sg = *Rao::CTest::makeAnObject();  
  45.     cout << "m_nValue :" << Rao::CTest::m_nValue << endl;  
namespace Rao
{
	class CTest
	{
	public:
		static CTest* makeAnObject()
		{
			 // 程序结束的时候 自动释放
			static CTest instance;
			return &instance;
		}
		~CTest()
		{
			cout << "CTest Destructor...." << endl;
		}
		static int m_nValue;
	private:
		CTest()
		{
			m_nValue++;
			cout << "CTest Constructor...." << endl;
		}
		
		CTest( const CTest& CopyCTest )
		{
			m_nValue++;
			cout << "CopyCTest Constructor...." << endl;
		}

		const  CTest& operator= ( const CTest& );
	};
}
main:
	int Rao::CTest::m_nValue;

	cout << "\n";
	cout << "use Constructor privatization :" << endl;
	Rao::CTest* RaoCTest = Rao::CTest::makeAnObject();
	cout << "m_nValue :" << Rao::CTest::m_nValue << endl;
	Rao::CTest* RaoCTest2 = Rao::CTest::makeAnObject();
	cout << "m_nValue :" << Rao::CTest::m_nValue << endl;

	// 调用拷贝构造函数
	Rao::CTest sg = *Rao::CTest::makeAnObject();
	cout << "m_nValue :" << Rao::CTest::m_nValue << endl;


 

类的成员访问控制
public : 公有访问接口
protected : 1)可以供类自身访问的成员 2)可以供下级子类访问的成员
private : 仅供类自身访问的成员


友元函数
简单理解为 : 由于类成员的访问控制机制,很好地实现了数据的隐藏与封装,类的成员变量一般定义为私有成员,成员函数一般定义为公有成员,以此来提供类与外界间的通信接口;但有特殊的情况,比如需要定义某个函数/某个类,这个函数/类不是类CA的一部分,但又需要频繁地访问类CA的隐藏信息,所以C++提供了一个"friend"关键字来完成这个任务。
友元函数和友元类都需要试一试--------------------------------------P172
但需要记住的一点 :
1)友元关系不能被继承。这一点很好理解,我们跟某个类是朋友,并不表示我们跟这个类的儿子(派生类)同样是朋友。
2)友元关系是单向的,不具有交换性。

 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4.   
  5. namespace Zeng  
  6. {  
  7.     class CTest_A  
  8.     {  
  9.     public:  
  10.         CTest_A( int iValue )  
  11.         {  
  12.             this->m_iValue = iValue;  
  13.         }  
  14.         void print()  
  15.         {  
  16.             cout << "CTest_A's m_iValue current value is : " << this->m_iValue << endl;  
  17.         }  
  18.         friend void firendFunction( const CTest_A& CA );  
  19.         friend class CTest_B;  
  20.     private:  
  21.         int m_iValue;  
  22.     };  
  23.   
  24.     class CTest_B  
  25.     {  
  26.     public:  
  27.         CTest_B()  
  28.         {  
  29.         }  
  30.         void print( const CTest_A& CA )  
  31.         {  
  32.             cout << "this's firend class CTest_B print : " << CA.m_iValue << endl;  
  33.         }  
  34.     private:  
  35.     }; // 友元类  
  36.   
  37.     void firendFunction( const CTest_A& CA )  
  38.     {  
  39.         cout << "this's firend function print : " << CA.m_iValue << endl;  
  40.     }  
  41. }  
  42.   
  43. int _tmain(int argc, _TCHAR* argv[])  
  44. {  
  45.     Zeng::CTest_A CA( 100 );  
  46.     firendFunction( CA );  
  47.   
  48.     cout << "\n";  
  49.     Zeng::CTest_B CB;  
  50.     CB.print( CA );  
  51.   
  52.     return 0;  

抽象一般分为属性抽象和行为抽象两种。前者寻找一类对象共有的属性或者状态变量,后者则寻找这类对象所具有的共同行为特征。在分析新的对象时,应该从属性和行为两个方面进行抽象和概括,提取对象的共有也行。有了抽象,那么就可以提取出来当做接口(虚函数),可以直接变成类的成员属性和成员函数。


如何在子类中调用从父类继承并且已经被重写的函数?--------------------


  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4.   
  5. namespace Zeng  
  6. {  
  7.     class CTest_A  
  8.     {  
  9.     public:  
  10.         CTest_A( int iValue )  
  11.         {  
  12.             this->m_iValue = iValue;  
  13.         }  
  14.         void print()  
  15.         {  
  16.             cout << "CTest_A's m_iValue current value is : " << this->m_iValue << endl;  
  17.         }  
  18.     private:  
  19.         int m_iValue;  
  20.     };  
  21.   
  22.     class CTest_B : public CTest_A  
  23.     {  
  24.     public:  
  25.         CTest_B( int iValue ) : CTest_A( iValue )  
  26.         {  
  27.             this->m_iValue = iValue;  
  28.         }  
  29.         void print()  
  30.         {  
  31.             cout << "CTest_B's m_iValue current value is : " << this->m_iValue << endl;  
  32.         }  
  33.     private:  
  34.         int m_iValue;  
  35.     }; // virtual CTest_A比普通的public CTest_A多了一个指向父类的指针  
  36. }  
  37.   
  38. int _tmain(int argc, _TCHAR* argv[])  
  39. {  
  40.     Zeng::CTest_A* CB2 = new Zeng::CTest_B( 8 ); // 构造函数的执行顺序是先父类在子类  
  41.     CB2->print(); // 此时调用的是父类的print函数,因为指针时指向CTest_A的,如果在CTest_B的print前面加virtual还调用CTest_B的  
  42.   
  43.     cout << "class CTest_A size is : " << sizeof( Zeng::CTest_A ) << endl;  
  44.     cout << "class CTest_B size is : " << sizeof( Zeng::CTest_B ) << endl;  
  45.   
  46.     return 0;  
  47. }  
#include "stdafx.h"
#include "iostream"
using namespace std;

namespace Zeng
{
	class CTest_A
	{
	public:
		CTest_A( int iValue )
		{
			this->m_iValue = iValue;
		}
		void print()
		{
			cout << "CTest_A's m_iValue current value is : " << this->m_iValue << endl;
		}
	private:
		int m_iValue;
	};

	class CTest_B : public CTest_A
	{
	public:
		CTest_B( int iValue ) : CTest_A( iValue )
		{
			this->m_iValue = iValue;
		}
		void print()
		{
			cout << "CTest_B's m_iValue current value is : " << this->m_iValue << endl;
		}
	private:
		int m_iValue;
	}; // virtual CTest_A比普通的public CTest_A多了一个指向父类的指针
}

int _tmain(int argc, _TCHAR* argv[])
{
	Zeng::CTest_A* CB2 = new Zeng::CTest_B( 8 ); // 构造函数的执行顺序是先父类在子类
	CB2->print(); // 此时调用的是父类的print函数,因为指针时指向CTest_A的,如果在CTest_B的print前面加virtual还调用CTest_B的

	cout << "class CTest_A size is : " << sizeof( Zeng::CTest_A ) << endl;
	cout << "class CTest_B size is : " << sizeof( Zeng::CTest_B ) << endl;

	return 0;
}




this指针 :
比如在类中


  1. class Base  
  2. {  
  3.     public:  
  4.         void SetValue( int nVal )  
  5.         {  
  6.             m_nVal = nVal;  
  7.         }  
  8.     private:  
  9.         int m_nVal;  
  10. }  
class Base
{
	public:
		void SetValue( int nVal )
		{
			m_nVal = nVal;
		}
	private:
		int m_nVal;
}



SetValue函数中并没有指明m_nVal成员变量到底属于哪一个对象类似的问题...其实编译器隐藏掉了,应该是this->m_nVal = nVal;当然在使用的时候,可以直接在这个变量前面显示的加上去。


但是,this指针在实际开发中的意义却是,用来返回指向对象本身的指针,以实现对象链式引用,或者避免对同一对象进行赋值操作。例如


  1. class Point  
  2. {  
  3.     public:  
  4.         Point( int x, int y ) : m_nX( x ), m_nY( y )  
  5.         {};  
  6.         void operator = (Point& pt)  
  7.         {  
  8.             // 判断传递进来而定参数是否是这个对象本身,是,则不进行赋值操作  
  9.             if( &pt == this )  
  10.             {  
  11.                 m_nX = pt.m_nX;  
  12.                 m_nY = pt.m_nY;  
  13.             }  
  14.         }  
  15.         // 移动点的位置  
  16.         Point& Move( int x, int y )  
  17.         {  
  18.             m_nX += x;  
  19.             m_nY += y;  
  20.             // 返回对象本身,这样可以利用函数返回值进行链式引用  
  21.             return *this;  
  22.         }  
  23.     private:  
  24.         int m_nX;  
  25.         int m_nY;  
  26. };  
  27.   
  28. Point pt1(2, 4);  
  29. Point pt2(0, 0);  
  30. // 自己给自己赋值 试试  
  31. pt1 = pt1;  
  32. // 移动一下,再移动一下 看看什么是返回对象的链式引用------------------------  
  33. pt1.Move( 1, 1 ).Move( 2, 4 );  
class Point
{
	public:
		Point( int x, int y ) : m_nX( x ), m_nY( y )
		{};
		void operator = (Point& pt)
		{
			// 判断传递进来而定参数是否是这个对象本身,是,则不进行赋值操作
			if( &pt == this )
			{
				m_nX = pt.m_nX;
				m_nY = pt.m_nY;
			}
		}
		// 移动点的位置
		Point& Move( int x, int y )
		{
			m_nX += x;
			m_nY += y;
			// 返回对象本身,这样可以利用函数返回值进行链式引用
			return *this;
		}
	private:
		int m_nX;
		int m_nY;
};

Point pt1(2, 4);
Point pt2(0, 0);
// 自己给自己赋值 试试
pt1 = pt1;
// 移动一下,再移动一下 看看什么是返回对象的链式引用------------------------
pt1.Move( 1, 1 ).Move( 2, 4 );



指针* :
1)指针加1或者减1,会使指针指向的地址增加或者减少一个对象的数据类型的长度。
2)指针类型的转换
虽然指针类型的转换可能会带来不可预料的麻烦,就行goto语句一样,比如

 
  1. int* pInt;  
  2. float* pFloat = ( float* )pInt;  
int* pInt;
float* pFloat = ( float* )pInt;


这种方法比较直接,但是非常粗鲁,因为他允许你在任何类型之间进行转换,另外这种类型的转换方式在程序语句中很难识别,代码阅读者可能会忽略类型转换的语句。
为了克服这些缺点,C++引入了新的类型转换操作符static_cast来代替上面的类型转换
static_cast<类型说明符>(表达式)
static_cast
指针的类型转换-------------------------------------------------------


  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4.   
  5. namespace Zeng  
  6. {  
  7.     class CTest_A  
  8.     {  
  9.     public:  
  10.         CTest_A()  
  11.         {}  
  12.         virtual void Print()  
  13.         {  
  14.             cout << "this's CTest_A's Print :" << endl;  
  15.         }  
  16.     };  
  17.     class CTest_B : public CTest_A  
  18.     {  
  19.     public:  
  20.         CTest_B()  
  21.         {}  
  22.         void Print()  
  23.         {  
  24.             cout << "this's CTest_B's Print :" << endl;  
  25.         }  
  26.     };  
  27.     class CTest_C  
  28.     {  
  29.     public:  
  30.         CTest_C()  
  31.         {}  
  32.         void Print()  
  33.         {  
  34.             cout << "this's CTest_C's Print :" << endl;  
  35.         }  
  36.     };  
  37.     class CTest_D  
  38.     {  
  39.     public:  
  40.         CTest_D() : m_iNum(14)  
  41.         {  
  42.         }  
  43.         void ConstPrint() const  
  44.         {  
  45.             cout << "ConstPrint print CTest_D m_iNum current value is :" << m_iNum << endl;  
  46.         }  
  47.         void Print()  
  48.         {  
  49.             cout << "Print print CTest_D m_iNum current value is :" << m_iNum << endl;  
  50.         }  
  51.         int m_iNum;  
  52.     }; // 用来测试const_cast转换操作符  
  53. }  
  54.   
  55. int _tmain(int argc, _TCHAR* argv[])  
  56. {  
  57.     cout << "CTest_B convert to CTest_A :" << endl;  
  58.     Zeng::CTest_B* B = new Zeng::CTest_B();  
  59.     Zeng::CTest_A* A = static_cast< Zeng::CTest_A* >( B );  
  60.     A->Print();  
  61.   
  62.   
  63.     cout << "\n";  
  64.     cout << "CTest_A convert to CTest_B :" << endl;  
  65.     Zeng::CTest_A* A2 = new Zeng::CTest_A();  
  66.     Zeng::CTest_B* B2 = static_cast< Zeng::CTest_B* >( A2 );  
  67.     B2->Print();  
  68.   
  69. /* 
  70.     cout << "\n"; 
  71.     cout << "CTest_B convert to CTest_C :" << endl; 
  72.     Zeng::CTest_B* B3 = new Zeng::CTest_B();  
  73.     Zeng::CTest_C* C = static_cast< Zeng::CTest_C* >( B3 ); 
  74.     // the CTest_B has nothing to do with CTest_C, so this convert been an error ! 
  75.     B2->Print(); 
  76. */  
  77.   
  78.     cout << "\n";  
  79.     cout << "CTest_B convert to CTest_C :" << endl;  
  80.     Zeng::CTest_B* B3 = new Zeng::CTest_B();   
  81.     Zeng::CTest_C* C = reinterpret_cast< Zeng::CTest_C* >( B3 );  
  82.     // reinterpret_cast should be convert CTest_B to CTest_C,  
  83.     C->Print();  
  84.   
  85.     cout << "\n";  
  86.     cout << "CTest_A dynamic_cast to CTest_B :" << endl;  
  87.     Zeng::CTest_A* A4 = new Zeng::CTest_A();  
  88.     Zeng::CTest_B* B4 = dynamic_cast< Zeng::CTest_B* >( A4 ); // dynamic_cast要求CTest_B必须要有虚函数  
  89. //  B4->Print(); // 就算是有虚函数,dynamic_cast在处理向下转行的时候,得到的也是NULL  
  90.   
  91.     cout << "\n";  
  92.     cout << "CTest_B dynamic_cast to CTest_A :" << endl;  
  93.     Zeng::CTest_B* A5 = new Zeng::CTest_B();  
  94.     Zeng::CTest_A* B5 = dynamic_cast< Zeng::CTest_A* >( A5 ); // dynamic_cast要求CTest_B必须要有虚函数  
  95.     B5->Print(); // 就算是有虚函数,dynamic_cast在处理向上转行的时候,得到的是和static_cast一样的结果  
  96.   
  97.     int iNum = 14;  
  98.     int* pINum = &iNum;  
  99.     char* pCTest = "a";  
  100. /*  pCTest = reinterpret_cast< int* >( pINum );*/  
  101.     cout << "pINum point value is : " << *pINum << endl;  
  102.     // reinterpret_cast可以在任意指针中转换,即使这两者之间没什么关系  
  103.     pINum = reinterpret_castint* >( pCTest );  
  104.     cout << "pINum point value is : " << *pINum << endl;   
  105.   
  106.   
  107.     cout << "\n";  
  108.     const int iNum2 = 14;  
  109.     const int* piNum = &iNum2;  
  110.     int* piValue = const_castint* >( piNum );  
  111.     *piValue = 70;  
  112.   
  113.     cout << "use operator const_cast current *piValue value is : " << *piValue << endl;  
  114.     cout << "use operator const_cast current *piNum value is : " << *piNum << endl;  
  115.     cout << "use operator const_cast current iNum value is : " << iNum2 << endl;  
  116.   
  117.     cout << "\n";  
  118.     const Zeng::CTest_D CD;  
  119. //  CD.m_iNum = 70; // error C3892: “CD”: 不能给常量赋值  
  120.     const Zeng::CTest_D* pCD = &CD;  
  121.   
  122.     Zeng::CTest_D* pCD2 = const_cast< Zeng::CTest_D * >( pCD );  
  123.     pCD2->m_iNum = 70;  
  124.     cout << "use const_cast operator as object :" << endl;  
  125.     cout << "pCD2 is not's const point, this point m_iNum value is" << endl;  
  126.     pCD2->Print();  
  127.     cout << "CD is a class object, this object m_iNum value is" << endl;  
  128.     CD.ConstPrint(); // const 对象只能访问class里面带有const的函数  
  129.     cout << "pCD is a const point, this point m_iNum value is" << endl;  
  130.     pCD->ConstPrint();  
  131.   
  132.     return 0;  
  133. }  
#include "stdafx.h"
#include "iostream"
using namespace std;

namespace Zeng
{
	class CTest_A
	{
	public:
		CTest_A()
		{}
		virtual void Print()
		{
			cout << "this's CTest_A's Print :" << endl;
		}
	};
	class CTest_B : public CTest_A
	{
	public:
		CTest_B()
		{}
		void Print()
		{
			cout << "this's CTest_B's Print :" << endl;
		}
	};
	class CTest_C
	{
	public:
		CTest_C()
		{}
		void Print()
		{
			cout << "this's CTest_C's Print :" << endl;
		}
	};
	class CTest_D
	{
	public:
		CTest_D() : m_iNum(14)
		{
		}
		void ConstPrint() const
		{
			cout << "ConstPrint print CTest_D m_iNum current value is :" << m_iNum << endl;
		}
		void Print()
		{
			cout << "Print print CTest_D m_iNum current value is :" << m_iNum << endl;
		}
		int m_iNum;
	}; // 用来测试const_cast转换操作符
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout << "CTest_B convert to CTest_A :" << endl;
	Zeng::CTest_B* B = new Zeng::CTest_B();
	Zeng::CTest_A* A = static_cast< Zeng::CTest_A* >( B );
	A->Print();


	cout << "\n";
	cout << "CTest_A convert to CTest_B :" << endl;
	Zeng::CTest_A* A2 = new Zeng::CTest_A();
	Zeng::CTest_B* B2 = static_cast< Zeng::CTest_B* >( A2 );
	B2->Print();

/*
	cout << "\n";
	cout << "CTest_B convert to CTest_C :" << endl;
	Zeng::CTest_B* B3 = new Zeng::CTest_B(); 
	Zeng::CTest_C* C = static_cast< Zeng::CTest_C* >( B3 );
	// the CTest_B has nothing to do with CTest_C, so this convert been an error !
	B2->Print();
*/

	cout << "\n";
	cout << "CTest_B convert to CTest_C :" << endl;
	Zeng::CTest_B* B3 = new Zeng::CTest_B(); 
	Zeng::CTest_C* C = reinterpret_cast< Zeng::CTest_C* >( B3 );
	// reinterpret_cast should be convert CTest_B to CTest_C,
	C->Print();

	cout << "\n";
	cout << "CTest_A dynamic_cast to CTest_B :" << endl;
	Zeng::CTest_A* A4 = new Zeng::CTest_A();
	Zeng::CTest_B* B4 = dynamic_cast< Zeng::CTest_B* >( A4 ); // dynamic_cast要求CTest_B必须要有虚函数
//	B4->Print(); // 就算是有虚函数,dynamic_cast在处理向下转行的时候,得到的也是NULL

	cout << "\n";
	cout << "CTest_B dynamic_cast to CTest_A :" << endl;
	Zeng::CTest_B* A5 = new Zeng::CTest_B();
	Zeng::CTest_A* B5 = dynamic_cast< Zeng::CTest_A* >( A5 ); // dynamic_cast要求CTest_B必须要有虚函数
	B5->Print(); // 就算是有虚函数,dynamic_cast在处理向上转行的时候,得到的是和static_cast一样的结果

	int iNum = 14;
	int* pINum = &iNum;
	char* pCTest = "a";
/*	pCTest = reinterpret_cast< int* >( pINum );*/
	cout << "pINum point value is : " << *pINum << endl;
	// reinterpret_cast可以在任意指针中转换,即使这两者之间没什么关系
	pINum = reinterpret_cast< int* >( pCTest );
	cout << "pINum point value is : " << *pINum << endl; 


	cout << "\n";
	const int iNum2 = 14;
	const int* piNum = &iNum2;
	int* piValue = const_cast< int* >( piNum );
	*piValue = 70;

	cout << "use operator const_cast current *piValue value is : " << *piValue << endl;
	cout << "use operator const_cast current *piNum value is : " << *piNum << endl;
	cout << "use operator const_cast current iNum value is : " << iNum2 << endl;

	cout << "\n";
	const Zeng::CTest_D CD;
//	CD.m_iNum = 70; // error C3892: “CD”: 不能给常量赋值
	const Zeng::CTest_D* pCD = &CD;

	Zeng::CTest_D* pCD2 = const_cast< Zeng::CTest_D * >( pCD );
	pCD2->m_iNum = 70;
	cout << "use const_cast operator as object :" << endl;
	cout << "pCD2 is not's const point, this point m_iNum value is" << endl;
	pCD2->Print();
	cout << "CD is a class object, this object m_iNum value is" << endl;
	CD.ConstPrint(); // const 对象只能访问class里面带有const的函数
	cout << "pCD is a const point, this point m_iNum value is" << endl;
	pCD->ConstPrint();

	return 0;
}




二级指针的使用** :
一个例子既可以知道


  1. char* arrMouth[] = { "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec" };  
  2. char** pMouth = arrMouth;  
  3. int nIndex;  
  4. cout << "请输入月份对应的数字 : " << endl;  
  5. cin >> nIndex;  
  6.   
  7. // 之所以是char*是因为每一个月份都是字符串类型的  
  8. char* pCurMonth = *( pMouth + ( nIndex - 1 ) );  
  9. cout << "对应的月份是 : " << pCurMonth << endl;  
  10. cout << "对应的月份是 : " << *pCurMonth << endl;  
	char* arrMouth[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
	char** pMouth = arrMouth;
	int nIndex;
	cout << "请输入月份对应的数字 : " << endl;
	cin >> nIndex;

	// 之所以是char*是因为每一个月份都是字符串类型的
	char* pCurMonth = *( pMouth + ( nIndex - 1 ) );
	cout << "对应的月份是 : " << pCurMonth << endl;
	cout << "对应的月份是 : " << *pCurMonth << endl;


指针在函数中的作用 :
1)在函数的参数中使用指针,在传递大数据的时候可以有效减少函数调用的开销


  1. void SumArray( const int* pArray, int nArrayCount, int* nSum )  
  2. {  
  3.     *nSum = 0;  
  4.   
  5.     // 遍历整个数组  
  6.     for (int i = 0; i < nArrayCount; i++)  
  7.     {  
  8.         *nSum += *pArray;  
  9.         pArray++;  
  10.     }  
  11. }  
  12.   
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.     cout << "指针作为函数参数:" << endl;  
  16.     int nArraySum;  
  17.     int iArray[5] = { 1, 2, 3, 4, 5};  
  18.   
  19.     SumArray( iArray, 5, &nArraySum );  
  20.     cout << "运算的和为:" << nArraySum << endl;  
  21.   
  22.     return 0;  
  23. }  
void SumArray( const int* pArray, int nArrayCount, int* nSum )
{
	*nSum = 0;

	// 遍历整个数组
	for (int i = 0; i < nArrayCount; i++)
	{
		*nSum += *pArray;
		pArray++;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	cout << "指针作为函数参数:" << endl;
	int nArraySum;
	int iArray[5] = { 1, 2, 3, 4, 5};

	SumArray( iArray, 5, &nArraySum );
	cout << "运算的和为:" << nArraySum << endl;

	return 0;
}

 

2)指针作为函数返回值
当函数的返回值是指针时,这个函数就是指针型函数。指针型函数通常用来获取一些指针变量的值。
在类中返回一个指针类型的成员变量,经常会使用到指针作为函数返回值


  1. char* GetName()  
  2. {  
  3.     return m_pName;  
  4. }  
char* GetName()
{
	return m_pName;
}


引用& :
1)引用的本质,就是变量的别名,通俗地讲,就是变量的绰号。对变量的引用进行任何操作,就是对变量本身的操作,就想不管是叫你小名还是叫你的绰号,都是在叫同一个人。


  1. cout << "use reference:" << endl;  
  2. int nIntValue = 99999;  
  3. int& rIntValue = nIntValue;  
  4. cout << "rIntValue:" << rIntValue << endl;  
  5. cout << "rIntValue memory address:" << &rIntValue << endl;  
  6. cout << "nIntValue:" << nIntValue << endl;  
  7. cout << "nIntValue memory address:" << &nIntValue << endl;  
  8.   
  9. rIntValue = 1;  
  10. cout << "modify rIntValue after:" << rIntValue << endl;  
  11. cout << "rIntValue memory address:" << &rIntValue << endl;  
  12. cout << "current nIntValue:" << nIntValue << endl;  
  13. cout << "nIntValue memory address:" << &nIntValue << endl;  
  14.   
  15. nIntValue = 8888;  
  16. cout << "modify nIntValue after:" << nIntValue << endl;  
  17. cout << "nIntValue memory address:" << &nIntValue << endl;  
  18. cout << "current rIntValue:" << rIntValue << endl;  
  19. cout << "rIntValue memory address:" << &rIntValue << endl;  
	cout << "use reference:" << endl;
	int nIntValue = 99999;
	int& rIntValue = nIntValue;
	cout << "rIntValue:" << rIntValue << endl;
	cout << "rIntValue memory address:" << &rIntValue << endl;
	cout << "nIntValue:" << nIntValue << endl;
	cout << "nIntValue memory address:" << &nIntValue << endl;

	rIntValue = 1;
	cout << "modify rIntValue after:" << rIntValue << endl;
	cout << "rIntValue memory address:" << &rIntValue << endl;
	cout << "current nIntValue:" << nIntValue << endl;
	cout << "nIntValue memory address:" << &nIntValue << endl;

	nIntValue = 8888;
	cout << "modify nIntValue after:" << nIntValue << endl;
	cout << "nIntValue memory address:" << &nIntValue << endl;
	cout << "current rIntValue:" << rIntValue << endl;
	cout << "rIntValue memory address:" << &rIntValue << endl;


 

2)在函数参数中使用,传递引用可以直接对这个参数进行修改


  1. void Increase( int& nVal )  
  2. {  
  3.     nVal += 1;  
  4. }  
void Increase( int& nVal )
{
	nVal += 1;
}


三种函数参数和返回值的方法 :
1)
传值 是指直接将实际参数的值复制给形参,完成参数的传递
形式简单自然,便于理解,代码可读性高

2)
传指针 是指将需要传递的数据的指针作为参数进行传递
效率高,可以同时传入传出参数

3)
传引用 将需要传递的数据的引用作为参数进行传递
效率高,可以同时传入传出参数,形式自然


异常处理
异常的使用,会降低程序的性能,但是,如果使用得当,有时也可以提高程序的性能。比如,如果函数的参数是指针,则需要在函数入口处对这个指针的有效性进行检查。


  1. double Divede( int a, int b )  
  2. {  
  3.     if ( 0 == b )  
  4.     {  
  5.         throw "除数不能为 0 ";  
  6.     }  
  7.     return ( double )a / b;  
  8. }  
  9.   
  10.     cout << "use exception deal : " << endl;  
  11.     try  
  12.     {  
  13.         Divede( 2, 0 );  
  14.         cout << "throw a exception : " << endl;  
  15.     }  
  16.     catch ( char* pMsg )  
  17.     {  
  18.         cout << "catch a exception : " << pMsg << endl;  
  19.     }  
  20.     catch (...)  
  21.     {  
  22.         cout << "catch a exception : " << endl;  
  23.     }  
  24.   
  25.     cout << "is this appcation exit ? : " << endl;  
double Divede( int a, int b )
{
	if ( 0 == b )
	{
		throw "除数不能为 0 ";
	}
	return ( double )a / b;
}

	cout << "use exception deal : " << endl;
	try
	{
		Divede( 2, 0 );
		cout << "throw a exception : " << endl;
	}
	catch ( char* pMsg )
	{
		cout << "catch a exception : " << pMsg << endl;
	}
	catch (...)
	{
		cout << "catch a exception : " << endl;
	}

	cout << "is this appcation exit ? : " << endl;


名字空间namespace :
主要在多人同时开发时候使用,避免冲突


  1. namespace Zeng  
  2. {  
  3.     class CTest  
  4.     {  
  5.     public:  
  6.         void Print()  
  7.         {  
  8.             cout << "this is namespace Zeng's Print" << endl;  
  9.         }  
  10.     };  
  11. }  
  12.   
  13.     cout << "use namespace Zeng ? : " << endl;  
  14.     Zeng::CTest CZengText;  
  15.     CZengText.Print();  
namespace Zeng
{
	class CTest
	{
	public:
		void Print()
		{
			cout << "this is namespace Zeng's Print" << endl;
		}
	};
}

	cout << "use namespace Zeng ? : " << endl;
	Zeng::CTest CZengText;
	CZengText.Print();


自定义类型的使用typedef :
后代前,以后使用byte就相当于使用了unsigned char


  1. typedef unsigned char byte;  
typedef unsigned char byte;


宏的使用#define
1)简单的使用
#define MAXSIZE 100
2)宏直接分配数组


  1. #define myInitArray(ArrayName, ArraySize, InitValue) byte ArrayName[ArraySize + 1] = InitValue  
#define myInitArray(ArrayName, ArraySize, InitValue) byte ArrayName[ArraySize + 1] = InitValue

 

3)宏中定义函数


  1. #ifndef SAFE_DELETE  
  2. #define SAFE_DELETE( p )        {           \  
  3.             if( NULL != p )             \  
  4.             {                           \  
  5.                 delete p; p = NULL;     \  
  6.                 cout << "safe delete..." << endl; \  
  7.             } }  
  8. #endif  
  9.   
  10. #ifndef SAFE_DELETE_ARRAY  
  11. #define SAFE_DELETE_ARRAY( p )      {           \  
  12.     if( NULL != p )             \  
  13. {                           \  
  14.     delete[] p; p = NULL;       \  
  15.     cout << "safe delete[]..." << endl; \  
  16. } }  
  17. #endif  
  18.   
  19.   
  20.     Zeng::CTest* CZengText2 = new Zeng::CTest;  
  21.     SAFE_DELETE( CZengText2 );  
#ifndef SAFE_DELETE
#define SAFE_DELETE( p )		{			\
			if( NULL != p )				\
			{							\
				delete p; p = NULL;		\
				cout << "safe delete..." << endl; \
			} }
#endif

#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY( p )		{			\
	if( NULL != p )				\
{							\
	delete[] p; p = NULL;		\
	cout << "safe delete[]..." << endl; \
} }
#endif


	Zeng::CTest* CZengText2 = new Zeng::CTest;
	SAFE_DELETE( CZengText2 );



用const保护数据
1)const定义常量


  1. const int number = 1;   // 声明一个整形常量并复制为1  
  2. const int* pNumber; // 声明一个常量型指针,指针所指向的变量的值不能改变,也就是一个常量  
  3. int const* pNumber; // 声明一个常量整型指针,意义同上  
  4. intconst pNumber = &number;       // 声明一个整型常量指针,指针不能修改  
  5. const intconst pNumber = &number;// 声明一个常量整型常量指针,指针和指针所指向的变量值都不能改变  
  6. const int& number = number; // 声明一个常量整型引用  
const int number = 1;	// 声明一个整形常量并复制为1
const int* pNumber;	// 声明一个常量型指针,指针所指向的变量的值不能改变,也就是一个常量
int const* pNumber;	// 声明一个常量整型指针,意义同上
int* const pNumber = &number;		// 声明一个整型常量指针,指针不能修改
const int* const pNumber = &number;// 声明一个常量整型常量指针,指针和指针所指向的变量值都不能改变
const int& number = number; // 声明一个常量整型引用


2)根据const实在*的位置判断 :
const在*左边,则表示const修饰的是int,这个指针指向的int变量的值不能修改,而指针本身的值是可变的;
如果const在*的右边,则表示const修饰的是指针,这个指针的值不能在声明后修改,所以在声明这样的指针时必须赋初值,而这个指针所指向的int变量的值是可变的。

3)在函数参数中加入const
表示这只是一个传入参数,在整个函数内部不能被修改。

4)修饰类成员函数
在声明类的成员函数时,如果在末尾加上const修饰,则表示在这个成员函数内不得改变该对象的任何数据。这种模式常用来表示"对象数据制度"的访问模式。


  1. namespace Zeng  
  2. {  
  3.     class CTest  
  4.     {  
  5.     public:  
  6.         void Print() const  
  7.         {  
  8.             m_nValue = 1;  
  9.             cout << "this is namespace Zeng's Print" << endl;  
  10.         }  
  11.     private:  
  12.         int m_nValue;  
  13.     };  
  14. }  
namespace Zeng
{
	class CTest
	{
	public:
		void Print() const
		{
			m_nValue = 1;
			cout << "this is namespace Zeng's Print" << endl;
		}
	private:
		int m_nValue;
	};
}

// 提示error : error C2166: 左值指定 const 对象

STL:
算法(algorithm)+容器(container)+迭代器(iterator) = STL

容器(container)
主要含有deque(双端队列)、queue(队列)、stack(堆栈容器)、vector(动态数组容器)、map multimap unordered_map unorderd_multimap(映射容器 由{键, 值}对组成)、set multiset unordered_set

unordered_multiset(集合容器)、algorithm(通用算法, 包括比较、交换、查找、排序等)、functional(模板类)、string(字符串类)、regex(正则表达式)、memory(定义了跟内存操作相关的组件, 例如智能指针等)

vector相对于数组来说,他可以合理利用空间,让程序有更大的可扩展性


函数模板
1)当编译器发现一个函数模板的调用后,将根据实参的实际数据类型来确认是否匹配函数模板中对应的形参,然后生成一个重载函数。根据参数类型的不同,一个函数模板可以随时变成各种不同的重载

函数,从而实集类型的处理。

2)比如max函数---------------------能够比较int、float、string
temple<typename 标识符>
返回值类型 函数名(形参表)
{
    //函数体
}


类模板
1)类模板的声明
temple<typename 标识符>
class 类名
{
    //类的定义
}

2)定义一个用于比较两个数的类模板compare


  1. #include "stdafx.h"  
  2. #include<vector>  
  3. #include<string>  
  4. #include<iostream>  
  5. #include<algorithm>  
  6. using namespace std;  
  7.   
  8. template <typename T>  
  9. T compare( const T a, const T b)  
  10. {  
  11.     return ( a > b ? a : b );  
  12. }  
  13. template <>  
  14. string compare( const string a, const string b)  
  15. {  
  16.     return ( a.size() > b.size() ? a : b );  
  17. }  
  18.   
  19. int main()  
  20. {  
  21.     const int ii = 10;  
  22.     const int ij = 20;  
  23.     cout << "return the max value is :  " << compare<int>( ii, ij ) << endl;  
  24.   
  25.     const float fi = 0.7f;  
  26.     const float fj = 1.2f;  
  27.     cout << "return the max value is :  " << compare<float>( fi, fj ) << endl;  
  28.   
  29.     const string strN = "aaaaaaaaaaa";  
  30.     const string strM = "zengraoli";  
  31.     cout << "return the max value is :  " << compare<string>( strN, strM ) << endl;  
  32.   
  33.     return 0;  
  34. }  
#include "stdafx.h"
#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;

template <typename T>
T compare( const T a, const T b)
{
	return ( a > b ? a : b );
}
template <>
string compare( const string a, const string b)
{
	return ( a.size() > b.size() ? a : b );
}

int main()
{
	const int ii = 10;
	const int ij = 20;
	cout << "return the max value is :  " << compare<int>( ii, ij ) << endl;

	const float fi = 0.7f;
	const float fj = 1.2f;
	cout << "return the max value is :  " << compare<float>( fi, fj ) << endl;

	const string strN = "aaaaaaaaaaa";
	const string strM = "zengraoli";
	cout << "return the max value is :  " << compare<string>( strN, strM ) << endl;

	return 0;
}


模板的实例化
1)隐式实例化
常用方式,实例化为
compare<int> intcompare(2, 3)

2)显示实例化
在声明时,直接在template关键字后接函数的声明,且函数标识符后接模板参数
比如:
template int compare<int> intcompare( int, int );

用模板使用通用算法-------------------------------------------------------------------------
actioncontainer 有一个撤销和恢复的通用功能


  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4.   
  5. template<typename T>  
  6. class CActionContainer  
  7. {  
  8. public:  
  9.     CActionContainer()  
  10.         : m_nRedoPos( 0 ), m_nUndoPos( 0 )  
  11.     {  
  12.     }  
  13.     void add( T value );  
  14.     T redo();  
  15.     T undo();  
  16. private:  
  17.     int m_nRedoPos;  
  18.     int m_nUndoPos;  
  19.     // Container size  
  20.     const static int ActionContainerSize = 5;  
  21.     // record array  
  22.     T m_RedoAction[ ActionContainerSize ];  
  23.     T m_UndoAction[ ActionContainerSize ];  
  24. };  
  25. template<typename T>  
  26. void CActionContainer<T>::add( T value )  
  27. {  
  28.     // if the container is full, adjust the pos of the container to add  
  29.     if ( m_nUndoPos > ActionContainerSize )  
  30.     {  
  31.         m_nUndoPos = m_nUndoPos - 1;  
  32.         for ( int i = 0; i < ActionContainerSize; i++ )  
  33.         {  
  34.             m_UndoAction[i] = m_UndoAction[ i + 1];  
  35.         }  
  36.     }  
  37.     m_UndoAction[ m_nUndoPos++ ] = value;  
  38. }  
  39.   
  40. // undo operator  
  41. template <typename T>  
  42. T CActionContainer<T>::undo()  
  43. {  
  44.     // copy the revocation action to restore of the array  
  45.     m_RedoAction[ m_nRedoPos++ ] = m_UndoAction[ --m_nUndoPos ];  
  46.     return m_UndoAction[ m_nUndoPos ];  
  47. }  
  48.   
  49. // redo operaor  
  50. template <typename T>  
  51. T CActionContainer<T>::redo()  
  52. {  
  53.     // copy recovery action to the revocation of the array  
  54.     m_UndoAction[ m_nUndoPos++ ] = m_RedoAction[ --m_nRedoPos ];  
  55.     return m_RedoAction[ m_nRedoPos ];  
  56. }  
  57.   
  58. int _tmain(int argc, _TCHAR* argv[])  
  59. {  
  60.     CActionContainer<int> intaction;  
  61.     intaction.add( 1 );  
  62.     intaction.add( 2 );  
  63.     intaction.add( 3 );  
  64.     intaction.add( 4 );  
  65.     intaction.add( 5 );  
  66.       
  67.     int iUndo = intaction.undo();  
  68.     cout << "pass undo current value is : " << iUndo << endl;  
  69.     iUndo = intaction.undo();  
  70.     cout << "second pass undo current value is : " << iUndo << endl;  
  71.   
  72.     int iRedo = intaction.redo();  
  73.     cout << "pass redo current value is : " << iRedo << endl;  
  74.     iRedo = intaction.redo();  
  75.     cout << "second pass redo current value is : " << iRedo << endl;  
  76.   
  77.     return 0;  
  78. }  
#include "stdafx.h"
#include "iostream"
using namespace std;

template<typename T>
class CActionContainer
{
public:
	CActionContainer()
		: m_nRedoPos( 0 ), m_nUndoPos( 0 )
	{
	}
	void add( T value );
	T redo();
	T undo();
private:
	int m_nRedoPos;
	int m_nUndoPos;
	// Container size
	const static int ActionContainerSize = 5;
	// record array
	T m_RedoAction[ ActionContainerSize ];
	T m_UndoAction[ ActionContainerSize ];
};
template<typename T>
void CActionContainer<T>::add( T value )
{
	// if the container is full, adjust the pos of the container to add
	if ( m_nUndoPos > ActionContainerSize )
	{
		m_nUndoPos = m_nUndoPos - 1;
		for ( int i = 0; i < ActionContainerSize; i++ )
		{
			m_UndoAction[i] = m_UndoAction[ i + 1];
		}
	}
	m_UndoAction[ m_nUndoPos++ ] = value;
}

// undo operator
template <typename T>
T CActionContainer<T>::undo()
{
	// copy the revocation action to restore of the array
	m_RedoAction[ m_nRedoPos++ ] = m_UndoAction[ --m_nUndoPos ];
	return m_UndoAction[ m_nUndoPos ];
}

// redo operaor
template <typename T>
T CActionContainer<T>::redo()
{
	// copy recovery action to the revocation of the array
	m_UndoAction[ m_nUndoPos++ ] = m_RedoAction[ --m_nRedoPos ];
	return m_RedoAction[ m_nRedoPos ];
}

int _tmain(int argc, _TCHAR* argv[])
{
	CActionContainer<int> intaction;
	intaction.add( 1 );
	intaction.add( 2 );
	intaction.add( 3 );
	intaction.add( 4 );
	intaction.add( 5 );
	
	int iUndo = intaction.undo();
	cout << "pass undo current value is : " << iUndo << endl;
	iUndo = intaction.undo();
	cout << "second pass undo current value is : " << iUndo << endl;

	int iRedo = intaction.redo();
	cout << "pass redo current value is : " << iRedo << endl;
	iRedo = intaction.redo();
	cout << "second pass redo current value is : " << iRedo << endl;

	return 0;
}


泛型编程
1)
通过使用模板,可以使程序具有更好的代码重用性。泛型编程就是一种大量使用模板来实现更好的代码重用性的编程方式

2)
泛型编程的代表作品STL是一种高效、泛型、可交互操作的软件组件。其中算法是泛型的,不与任何特定的数据结构或对象类型联系在一起。

STL容器
1)
顺序容器
deque(双端队列)、list(线性表)、vector(动态数组容器)
基于这三种基本的顺序容器又可以构造出一些专门的容器,用于比较特殊的数据结构,包括heap(堆)、stack(栈)、queue(队列)、priority queue(优先队列)

2)
关联容器
所容纳的对象时有{键、值}对组成

3)
操作容器中的数据元素

接受用户输入并将数据保存到容器中
在开始位置插入一个数据
删除容器中的前三个数据
清空容器中的所有数据


  1. #include "stdafx.h"  
  2. #include<vector>  
  3. #include<string>  
  4. #include<iostream>  
  5. #include<algorithm>  
  6. using namespace std;  
  7.   
  8. void vecDisplay( const float fValue )  
  9. {  
  10.     cout << "current value is : " << fValue << endl;  
  11. }  
  12.   
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.     vector<float> vecScore;  
  16.     float fi = 0.0f;  
  17.     for ( int i = 0; i < 5; i++ )  
  18.     {  
  19.         cin >> fi;  
  20.         vecScore.push_back(fi);  
  21.     }  
  22.     cout << "input the value : " << endl;  
  23.     for_each( vecScore.begin(), vecScore.end(), vecDisplay );  
  24.   
  25.     const float fj = 0.02f;  
  26.     vecScore.insert( vecScore.begin(), fj );  
  27.     cout << "\n";  
  28.     cout << "in the begin insert a number 0.02 : " << endl;  
  29.     for_each( vecScore.begin(), vecScore.end(), vecDisplay );  
  30.   
  31.     vecScore.erase( vecScore.begin() );  
  32.     vecScore.erase( vecScore.begin() );  
  33.     vecScore.erase( vecScore.begin() );  
  34.     cout << "\n";  
  35.     cout << "delete vec in the before three number : " << endl;  
  36.     for_each( vecScore.begin(), vecScore.end(), vecDisplay );  
  37.   
  38.     vecScore.clear();  
  39.     cout << "\n";  
  40.     cout << "clear vec : " << endl;  
  41.     for_each( vecScore.begin(), vecScore.end(), vecDisplay );  
  42.     return 0;  
  43. }  
#include "stdafx.h"
#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;

void vecDisplay( const float fValue )
{
	cout << "current value is : " << fValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<float> vecScore;
	float fi = 0.0f;
	for ( int i = 0; i < 5; i++ )
	{
		cin >> fi;
		vecScore.push_back(fi);
	}
	cout << "input the value : " << endl;
	for_each( vecScore.begin(), vecScore.end(), vecDisplay );

	const float fj = 0.02f;
	vecScore.insert( vecScore.begin(), fj );
	cout << "\n";
	cout << "in the begin insert a number 0.02 : " << endl;
	for_each( vecScore.begin(), vecScore.end(), vecDisplay );

	vecScore.erase( vecScore.begin() );
	vecScore.erase( vecScore.begin() );
	vecScore.erase( vecScore.begin() );
	cout << "\n";
	cout << "delete vec in the before three number : " << endl;
	for_each( vecScore.begin(), vecScore.end(), vecDisplay );

	vecScore.clear();
	cout << "\n";
	cout << "clear vec : " << endl;
	for_each( vecScore.begin(), vecScore.end(), vecDisplay );
	return 0;
}


STL迭代器
1)
容器和算法结合起来的黏合剂
和指针的区别,迭代器不一定具有地址值

2)
按照使用的目的不同,各个容器都提供了多种类型的迭代器。比如只读迭代器,前移迭代器等。跟指针类似迭代器前面加上*运算符能够获取这个迭代器所指向的数据;可以使用++或者--来将迭代器向

前或者向后移动一个位置,让它指向容器中的其他位置的数据元素。如果迭代器到达容器中的最后一个元素的后面,则迭代器编程past_the_end值,使用past_the_end值的迭代器来访问数据元素是非法

的,就好像使用NULL值的指针一样。

3)遍历容器


  1. #include "stdafx.h"  
  2. #include<vector>  
  3. #include<string>  
  4. #include<iostream>  
  5. #include<algorithm>  
  6. using namespace std;  
  7.   
  8. int main()  
  9. {  
  10.     vector<int> vecScore;  
  11.     vecScore.push_back( 50 );  
  12.     vecScore.push_back( 60 );  
  13.     vecScore.push_back( 70 );  
  14.     vecScore.push_back( 80 );  
  15.     vecScore.push_back( 90 );  
  16.   
  17.     vector<int>::iterator it;  
  18.     for ( it = vecScore.begin(); it != vecScore.end(); it++ )  
  19.     {  
  20.         cout << "print current value : " << ( *it ) << endl;  
  21.     }  
  22.   
  23.     return 0;  
  24. }  
#include "stdafx.h"
#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;

int main()
{
	vector<int> vecScore;
	vecScore.push_back( 50 );
	vecScore.push_back( 60 );
	vecScore.push_back( 70 );
	vecScore.push_back( 80 );
	vecScore.push_back( 90 );

	vector<int>::iterator it;
	for ( it = vecScore.begin(); it != vecScore.end(); it++ )
	{
		cout << "print current value : " << ( *it ) << endl;
	}

	return 0;
}

4)一般使用
a、对于对象,一般存放该对象的指针
b、小心清理容器中保存的对象指针,如果容器中保存的是对象,那么在容器析构的时候容器会自动清理这些对象。但是,如果存放对象指针,那么在容器析构的时候,首先要释放这些指针所指向的对象。

  1. #include "stdafx.h"  
  2. #include "vector"  
  3. #include "string"  
  4. #include "algorithm"  
  5. #include "iostream"  
  6. using namespace std;  
  7.   
  8. class CStudent  
  9. {  
  10. public:  
  11.     CStudent( int iHeight ) : m_nHeight( iHeight )  
  12.     {  
  13.   
  14.     }  
  15.     int GetHeight() const  
  16.     {  
  17.         return m_nHeight;  
  18.     }  
  19. private:  
  20.     int m_nHeight;  
  21. };  
  22.   
  23. void vecDisplay( CStudent* pSt )  
  24. {  
  25.     cout << "current value is : " << pSt->GetHeight() << endl;  
  26. }  
  27.   
  28. int _tmain(int argc, _TCHAR* argv[])  
  29. {  
  30.     vector<CStudent *> vecStudent;  
  31.     CStudent* CTest_A = new CStudent( 165 );  
  32.     CStudent* CTest_B = new CStudent( 175 );  
  33.     CStudent* CTest_C = new CStudent( 185 );  
  34.     vecStudent.push_back( CTest_A );  
  35.     vecStudent.push_back( CTest_B );  
  36.     vecStudent.push_back( CTest_C );  
  37.   
  38.     cout << "Init vector : " << endl;  
  39.     for_each( vecStudent.begin(), vecStudent.end(), vecDisplay );  
  40.   
  41.     vector<CStudent *>::iterator it;  
  42.     for ( it = vecStudent.begin(); it != vecStudent.end(); it++ )  
  43.     {  
  44.         if ( NULL != ( *it ))  
  45.         {  
  46.             delete ( *it );  
  47.         }  
  48.         ( *it ) = NULL;  
  49.     }  
  50.     cout << "clear this point vector" << endl;  
  51.     vecStudent.clear();  
  52.   
  53.     return 0;  
  54. }  
#include "stdafx.h"
#include "vector"
#include "string"
#include "algorithm"
#include "iostream"
using namespace std;

class CStudent
{
public:
	CStudent( int iHeight ) : m_nHeight( iHeight )
	{

	}
	int GetHeight() const
	{
		return m_nHeight;
	}
private:
	int m_nHeight;
};

void vecDisplay( CStudent* pSt )
{
	cout << "current value is : " << pSt->GetHeight() << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<CStudent *> vecStudent;
	CStudent* CTest_A = new CStudent( 165 );
	CStudent* CTest_B = new CStudent( 175 );
	CStudent* CTest_C = new CStudent( 185 );
	vecStudent.push_back( CTest_A );
	vecStudent.push_back( CTest_B );
	vecStudent.push_back( CTest_C );

	cout << "Init vector : " << endl;
	for_each( vecStudent.begin(), vecStudent.end(), vecDisplay );

	vector<CStudent *>::iterator it;
	for ( it = vecStudent.begin(); it != vecStudent.end(); it++ )
	{
		if ( NULL != ( *it ))
		{
			delete ( *it );
		}
		( *it ) = NULL;
	}
	cout << "clear this point vector" << endl;
	vecStudent.clear();

	return 0;
}

c、如果需要将某个对象保存到容器中,实际上STL会重新生成一个此对象的拷贝,然后将这个拷贝保存在容器中,源对象不再使用。所以,当要保存的对象中含有指针类型成员变量时,要为容器中的对

象实现拷贝构造函数和赋值操作符。
--------------------------------------------------------------

  1. #include "stdafx.h"  
  2. #include "vector"  
  3. #include "string"  
  4. #include "algorithm"  
  5. #include "iostream"  
  6. using namespace std;  
  7.   
  8. class CStudent  
  9. {  
  10. public:  
  11.     CStudent( const char* strName, const int iHeight)  
  12.     {  
  13.         m_nHeight = iHeight;  
  14.         m_strName = new char[ strlen( strName + 1 ) ];  
  15.         strcpy( m_strName, strName );  
  16.     }  
  17.     CStudent( const CStudent& st )  
  18.     {  
  19.         m_nHeight = st.m_nHeight;  
  20.         m_strName = new char[ strlen( st.m_strName ) ];  
  21.         strcpy( m_strName, st.m_strName );  
  22.     }  
  23.     CStudent& operator= ( const CStudent& st )  
  24.     {  
  25.         // to prevent self assignment  
  26.         if ( this == &st )  
  27.         {  
  28.             return *this;  
  29.         }  
  30.         m_nHeight = st.m_nHeight;  
  31.         m_strName = new char[ strlen( st.m_strName ) ];  
  32.         strcpy( m_strName, st.m_strName );  
  33.         return *this;  
  34.     }  
  35.     ~CStudent()  
  36.     {  
  37.         if ( NULL != m_strName )  
  38.         {  
  39.             delete[] m_strName;  
  40.             m_strName = NULL;  
  41.         }  
  42.     }  
  43.     char* GetName() const  
  44.     {  
  45.         return m_strName;  
  46.     }  
  47.     int GetHeight() const  
  48.     {  
  49.         return m_nHeight;  
  50.     }  
  51. private:  
  52.     int m_nHeight;  
  53.     char* m_strName;  
  54. };  
  55.   
  56. void vecDisplay( const CStudent st )  
  57. {  
  58.     cout << "the student name is : " << st.GetName()<< endl;  
  59. }  
  60.   
  61. int _tmain(int argc, _TCHAR* argv[])  
  62. {  
  63.     // Init  
  64.     vector<CStudent> vecStudent;  
  65.     CStudent Test_A( "zengraoli1", 155 );  
  66.     CStudent Test_B( "zengraoli2", 165 );  
  67.     CStudent Test_C( "zengraoli3", 175 );  
  68.   
  69.     Test_A = Test_B; // Test_A已经构造过了,所以这时进入的事重载的=操作符  
  70.     CStudent Test_D = Test_C; // Test_D没构造过,所以这时进入拷贝构造函数  
  71.   
  72.     vecStudent.push_back(Test_A);  
  73.     vecStudent.push_back(Test_B);  
  74.     vecStudent.push_back(Test_C);  
  75.   
  76.     cout << "output vector element : " << endl;  
  77.     for_each( vecStudent.begin(), vecStudent.end(), vecDisplay );  
  78.   
  79.     return 0;  
  80. }  
#include "stdafx.h"
#include "vector"
#include "string"
#include "algorithm"
#include "iostream"
using namespace std;

class CStudent
{
public:
	CStudent( const char* strName, const int iHeight)
	{
		m_nHeight = iHeight;
		m_strName = new char[ strlen( strName + 1 ) ];
		strcpy( m_strName, strName );
	}
	CStudent( const CStudent& st )
	{
		m_nHeight = st.m_nHeight;
		m_strName = new char[ strlen( st.m_strName ) ];
		strcpy( m_strName, st.m_strName );
	}
	CStudent& operator= ( const CStudent& st )
	{
		// to prevent self assignment
		if ( this == &st )
		{
			return *this;
		}
		m_nHeight = st.m_nHeight;
		m_strName = new char[ strlen( st.m_strName ) ];
		strcpy( m_strName, st.m_strName );
		return *this;
	}
	~CStudent()
	{
		if ( NULL != m_strName )
		{
			delete[] m_strName;
			m_strName = NULL;
		}
	}
	char* GetName() const
	{
		return m_strName;
	}
	int GetHeight() const
	{
		return m_nHeight;
	}
private:
	int m_nHeight;
	char* m_strName;
};

void vecDisplay( const CStudent st )
{
	cout << "the student name is : " << st.GetName()<< endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	// Init
	vector<CStudent> vecStudent;
	CStudent Test_A( "zengraoli1", 155 );
	CStudent Test_B( "zengraoli2", 165 );
	CStudent Test_C( "zengraoli3", 175 );

	Test_A = Test_B; // Test_A已经构造过了,所以这时进入的事重载的=操作符
	CStudent Test_D = Test_C; // Test_D没构造过,所以这时进入拷贝构造函数

	vecStudent.push_back(Test_A);
	vecStudent.push_back(Test_B);
	vecStudent.push_back(Test_C);

	cout << "output vector element : " << endl;
	for_each( vecStudent.begin(), vecStudent.end(), vecDisplay );

	return 0;
}

d、删除一个容器中大于某个数
删除的时候要注意:
    如在for循环中加上it++,那么删除的时候会后移一个。可以不再for中写it++,而在else部分写
    删除一个数的时候,不能仅仅是vecStudent.erase( it );必须要it = vecStudent.erase( it );记录,这是因为STL里的所有容器类中的erase实现都会返回一个迭代器,这个迭代器指向"当前删除

元素的后续元素,或者是end()"
--------------------------------------------------------------

  1. #include "stdafx.h"  
  2. #include "vector"  
  3. #include "string"  
  4. #include "algorithm"  
  5. #include "iostream"  
  6. using namespace std;  
  7.   
  8. class CStudent  
  9. {  
  10. public:  
  11.     CStudent( int iHeight ) : m_nHeight( iHeight )  
  12.     {  
  13.   
  14.     }  
  15.     int GetHeight() const  
  16.     {  
  17.         return m_nHeight;  
  18.     }  
  19. private:  
  20.     int m_nHeight;  
  21. };  
  22.   
  23. void vecDisplay( CStudent* pSt )  
  24. {  
  25.     cout << "current value is : " << pSt->GetHeight() << endl;  
  26. }  
  27.   
  28. int _tmain(int argc, _TCHAR* argv[])  
  29. {  
  30.     vector<CStudent *> vecStudent;  
  31.     CStudent* CTest_A = new CStudent( 165 );  
  32.     CStudent* CTest_B = new CStudent( 175 );  
  33.     CStudent* CTest_C = new CStudent( 185 );  
  34.     vecStudent.push_back( CTest_A );  
  35.     vecStudent.push_back( CTest_B );  
  36.     vecStudent.push_back( CTest_C );  
  37.   
  38.     cout << "Init vector : " << endl;  
  39.     for_each( vecStudent.begin(), vecStudent.end(), vecDisplay );  
  40.   
  41.   
  42.     vector<CStudent *>::iterator it;  
  43.     for ( it = vecStudent.begin(); it != vecStudent.end(); )  
  44.     {  
  45.         if ( ( *it )->GetHeight() < 180 )  
  46.         {  
  47.             delete ( *it );  
  48.             ( *it ) = NULL;  
  49.             it = vecStudent.erase( it );  
  50.         }  
  51.         else  
  52.         {  
  53.             it++;  
  54.         }  
  55.     }  
  56.     cout << "\n";  
  57.     cout << "delete smaller then 180 : " << endl;  
  58.     for_each( vecStudent.begin(), vecStudent.end(), vecDisplay );  
  59.     return 0;  

怎样选择STL容器类型
vector : 需要保存大量数据的时候
map : 用来实现查找表,或者用来存储稀疏数组或稀疏矩阵
list : 频繁地对序列的中部进行插入和删除操作
deque : 当大部分插入和删除发生在序列的头部或尾部时
array : 固定长度的数组


STL算法
1)用for_each()算法遍历容器中的数据元素

for_each()的参数分别是开始位置、结束位置、处理函数

 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4. #include "vector"  
  5. #include "algorithm"  
  6.   
  7. void vecDisplay( const int iValue )   
  8. {  
  9.     cout << "current value add 10 : " << iValue + 10 << endl;  
  10. }  
  11.   
  12. int _tmain(int argc, _TCHAR* argv[])  
  13. {  
  14.     vector<int> vecSalary;  
  15.     vecSalary.push_back( 10 );  
  16.     vecSalary.push_back( 20 );  
  17.     vecSalary.push_back( 30 );  
  18.     vecSalary.push_back( 40 );  
  19.     vecSalary.push_back( 50 );  
  20.   
  21.     cout << "display the value:" << endl;  
  22.     for_each( vecSalary.begin(), vecSalary.end(), vecDisplay );  
  23.   
  24.   
  25.     return 0;  
  26. }  
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "vector"
#include "algorithm"

void vecDisplay( const int iValue ) 
{
	cout << "current value add 10 : " << iValue + 10 << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> vecSalary;
	vecSalary.push_back( 10 );
	vecSalary.push_back( 20 );
	vecSalary.push_back( 30 );
	vecSalary.push_back( 40 );
	vecSalary.push_back( 50 );

	cout << "display the value:" << endl;
	for_each( vecSalary.begin(), vecSalary.end(), vecDisplay );


	return 0;
}

2)用find算法实现线性查找-----判断容器中是否存在特定的数据

find()的参数分别是开始位置、结束位置、要查找的数据

 
  1. #include "stdafx.h"  
  2. #include "vector"  
  3. #include "algorithm"  
  4. #include "string"  
  5. #include "iostream"  
  6. using namespace std;  
  7.   
  8. int _tmain(int argc, _TCHAR* argv[])  
  9. {  
  10.   
  11.     vector<string> vecStudentName;  
  12.     vecStudentName.push_back( "zengraoli" );  
  13.     vecStudentName.push_back( "125308501" );  
  14.     vecStudentName.push_back( "test" );  
  15.     vecStudentName.push_back( "find" );  
  16.   
  17.     const string strFindName = "125308501";  
  18.     vector<string>::iterator it = find( vecStudentName.begin(), vecStudentName.end(), strFindName );  
  19.     if (vecStudentName.end() != it)  
  20.     {  
  21.         cout << "vecStudentName is exist this string 125308501 !" << endl;  
  22.     }  
  23.     it = find( vecStudentName.begin(), vecStudentName.end(), "125308502" );  
  24.     if ( vecStudentName.end() == it )  
  25.     {  
  26.         cout << "vecStudentName isn't exist this string 125308502 !" << endl;  
  27.     }  
  28.   
  29.   
  30.     return 0;  
  31. }  
#include "stdafx.h"
#include "vector"
#include "algorithm"
#include "string"
#include "iostream"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

	vector<string> vecStudentName;
	vecStudentName.push_back( "zengraoli" );
	vecStudentName.push_back( "125308501" );
	vecStudentName.push_back( "test" );
	vecStudentName.push_back( "find" );

	const string strFindName = "125308501";
	vector<string>::iterator it = find( vecStudentName.begin(), vecStudentName.end(), strFindName );
	if (vecStudentName.end() != it)
	{
		cout << "vecStudentName is exist this string 125308501 !" << endl;
	}
	it = find( vecStudentName.begin(), vecStudentName.end(), "125308502" );
	if ( vecStudentName.end() == it )
	{
		cout << "vecStudentName isn't exist this string 125308502 !" << endl;
	}


	return 0;
}

3)用find_if()算法实现线性查找-----判断容器中是否存在指定范围的数据

find_if()的参数分别是开始位置、结束位置、所定义的要查找的条件(以bool(int)函数来表示)


 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4. #include "algorithm"  
  5. #include "vector"  
  6.   
  7. #define FIND_VALUE_TERMS 6  
  8.   
  9. bool isPass( int n )  
  10. {  
  11.     return n >= FIND_VALUE_TERMS;  
  12. }  
  13.   
  14. void vecDisplay( int iValue )  
  15. {  
  16.     cout << "current container value is : " << iValue << endl;  
  17. }  
  18.   
  19. int _tmain(int argc, _TCHAR* argv[])  
  20. {  
  21.     vector<int> vecScores;  
  22.     for ( int i = 1; i <= 10; i++ )  
  23.     {  
  24.         vecScores.push_back( i );  
  25.     }  
  26.   
  27.     vector< int >::iterator it = vecScores.begin();  
  28.     do   
  29.     {  
  30.         it = find_if( it, vecScores.end(), isPass );  
  31.         if (it != vecScores.end())  
  32.         {  
  33.             cout << "meet the conditions : " << ( *it ) << endl;  
  34.             it++; // this iterator point next  
  35.         }  
  36.         else  
  37.         {  
  38.             break;  
  39.         }  
  40.     } while (true);  
  41.   
  42.     return 0;  
  43. }  
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "algorithm"
#include "vector"

#define FIND_VALUE_TERMS 6

bool isPass( int n )
{
	return n >= FIND_VALUE_TERMS;
}

void vecDisplay( int iValue )
{
	cout << "current container value is : " << iValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> vecScores;
	for ( int i = 1; i <= 10; i++ )
	{
		vecScores.push_back( i );
	}

	vector< int >::iterator it = vecScores.begin();
	do 
	{
		it = find_if( it, vecScores.end(), isPass );
		if (it != vecScores.end())
		{
			cout << "meet the conditions : " << ( *it ) << endl;
			it++; // this iterator point next
		}
		else
		{
			break;
		}
	} while (true);

	return 0;
}

4)用remove()实现移除、replace()实现替换
 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4. #include "algorithm"  
  5. #include "vector"  
  6.   
  7. #define FIND_VALUE_TERMS 6  
  8.   
  9. void vecDisplay( int iValue )  
  10. {  
  11.     cout << "current container value is : " << iValue << endl;  
  12. }  
  13.   
  14. int _tmain(int argc, _TCHAR* argv[])  
  15. {  
  16.     vector<int> vecScores;  
  17.     for ( int i = 1; i <= 10; i++ )  
  18.     {  
  19.         vecScores.push_back( i );  
  20.     //  vecScores.push_back( 9 );  
  21.     }  
  22.   
  23.     cout << "used function remove" << endl;  
  24.     const int removeValue = 8;  
  25.     remove( vecScores.begin(), vecScores.end(), removeValue );  
  26.     for_each( vecScores.begin(), vecScores.end(), vecDisplay );  
  27.   
  28.     cout << "\n";  
  29.     cout << "used function replace" << endl;  
  30.     const int replaceValue = 9;  
  31.     const int newValue = 999;  
  32.     replace( vecScores.begin(), vecScores.end(),replaceValue, newValue );  
  33.     for_each( vecScores.begin(), vecScores.end(), vecDisplay );  
  34.   
  35.     return 0;  
  36. }  
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "algorithm"
#include "vector"

#define FIND_VALUE_TERMS 6

void vecDisplay( int iValue )
{
	cout << "current container value is : " << iValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> vecScores;
	for ( int i = 1; i <= 10; i++ )
	{
		vecScores.push_back( i );
	//	vecScores.push_back( 9 );
	}

	cout << "used function remove" << endl;
	const int removeValue = 8;
	remove( vecScores.begin(), vecScores.end(), removeValue );
	for_each( vecScores.begin(), vecScores.end(), vecDisplay );

	cout << "\n";
	cout << "used function replace" << endl;
	const int replaceValue = 9;
	const int newValue = 999;
	replace( vecScores.begin(), vecScores.end(),replaceValue, newValue );
	for_each( vecScores.begin(), vecScores.end(), vecDisplay );

	return 0;
}

5)复制容器元素 : copy()

有时需要将一个容器中的元素复制到另一个容器中区,来完成数据的备份或者进行其他处理。
vector<float>::iterator lastPos在使用的时候,指向的是某个具体的数据而不是该数据的pos。
 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4. #include "vector"  
  5. #include "algorithm"  
  6.   
  7. void vecDisplay( const int iValue )   
  8. {  
  9.     cout << "current container value is: " << iValue << endl;  
  10. }  
  11.   
  12. int _tmain(int argc, _TCHAR* argv[])  
  13. {  
  14.     vector<float> vecScoreFirst;  
  15.     vector<float> vecScoreSecond;  
  16.     vector<float> vecScore;  
  17.   
  18.     for ( int i = 0; i < 10; i++ )  
  19.     {  
  20.         vecScoreFirst.push_back( 60.0f + i );  
  21.     }  
  22.     cout << "vecScoreFirst current value:" << endl;  
  23.     for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );  
  24.   
  25.     for ( int i = 0; i < 10; i++ )  
  26.     {  
  27.         vecScoreSecond.push_back( 80.0f + i );  
  28.     }  
  29.     cout << "\n" << endl;  
  30.     cout << "vecScoreSecond current value:" << endl;  
  31.     for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );  
  32.   
  33.   
  34.     vecScore.resize( vecScoreFirst.size() + vecScoreSecond.size() ); // resize vecScore  
  35.     vector< float >::iterator lastPos = copy( vecScoreFirst.begin(), vecScoreFirst.end(), vecScore.begin() );  
  36.     copy( vecScoreSecond.begin(), vecScoreSecond.end(), lastPos );  
  37.   
  38.     cout << "\n" << endl;  
  39.     cout << "vecScore current value:" << endl;  
  40.     for_each( vecScore.begin(), vecScore.end(), vecDisplay );  
  41.   
  42.     return 0;  
  43. }  
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "vector"
#include "algorithm"

void vecDisplay( const int iValue ) 
{
	cout << "current container value is: " << iValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<float> vecScoreFirst;
	vector<float> vecScoreSecond;
	vector<float> vecScore;

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreFirst.push_back( 60.0f + i );
	}
	cout << "vecScoreFirst current value:" << endl;
	for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreSecond.push_back( 80.0f + i );
	}
	cout << "\n" << endl;
	cout << "vecScoreSecond current value:" << endl;
	for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );


	vecScore.resize( vecScoreFirst.size() + vecScoreSecond.size() ); // resize vecScore
	vector< float >::iterator lastPos = copy( vecScoreFirst.begin(), vecScoreFirst.end(), vecScore.begin() );
	copy( vecScoreSecond.begin(), vecScoreSecond.end(), lastPos );

	cout << "\n" << endl;
	cout << "vecScore current value:" << endl;
	for_each( vecScore.begin(), vecScore.end(), vecDisplay );

	return 0;
}

6)复制容器元素 : copy_backward()
从后向前覆盖
 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4. #include "vector"  
  5. #include "algorithm"  
  6.   
  7. void vecDisplay( const int iValue )   
  8. {  
  9.     cout << "current container value is: " << iValue << endl;  
  10. }  
  11.   
  12. int _tmain(int argc, _TCHAR* argv[])  
  13. {  
  14.     vector<float> vecScoreFirst;  
  15.     vector<float> vecScoreSecond;  
  16.     vector<float> vecScore;  
  17.   
  18.     for ( int i = 0; i < 10; i++ )  
  19.     {  
  20.         vecScoreFirst.push_back( 60.0f + i );  
  21.     }  
  22.     cout << "vecScoreFirst current value:" << endl;  
  23.     for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );  
  24.   
  25.     for ( int i = 0; i < 10; i++ )  
  26.     {  
  27.         vecScoreSecond.push_back( 80.0f + i );  
  28.     }  
  29.     cout << "\n" << endl;  
  30.     cout << "vecScoreSecond current value:" << endl;  
  31.     for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );  
  32.   
  33.     cout << "\n" << endl;  
  34.     vecScore.resize( vecScoreFirst.size() + vecScoreSecond.size() ); // resize vecScore  
  35.     cout << "vecScore size is : " << vecScore.size() << endl;  
  36.   
  37.     copy( vecScoreFirst.begin(), vecScoreFirst.end(), vecScore.begin() );  
  38.     copy_backward( vecScoreSecond.begin(), vecScoreSecond.end(), vecScore.end() );  
  39.   
  40.     cout << "\n" << endl;  
  41.     cout << "vecScore current value:" << endl;  
  42.     for_each( vecScore.begin(), vecScore.end(), vecDisplay );  
  43.   
  44.     return 0;  
  45. }  
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "vector"
#include "algorithm"

void vecDisplay( const int iValue ) 
{
	cout << "current container value is: " << iValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<float> vecScoreFirst;
	vector<float> vecScoreSecond;
	vector<float> vecScore;

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreFirst.push_back( 60.0f + i );
	}
	cout << "vecScoreFirst current value:" << endl;
	for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreSecond.push_back( 80.0f + i );
	}
	cout << "\n" << endl;
	cout << "vecScoreSecond current value:" << endl;
	for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );

	cout << "\n" << endl;
	vecScore.resize( vecScoreFirst.size() + vecScoreSecond.size() ); // resize vecScore
	cout << "vecScore size is : " << vecScore.size() << endl;

	copy( vecScoreFirst.begin(), vecScoreFirst.end(), vecScore.begin() );
	copy_backward( vecScoreSecond.begin(), vecScoreSecond.end(), vecScore.end() );

	cout << "\n" << endl;
	cout << "vecScore current value:" << endl;
	for_each( vecScore.begin(), vecScore.end(), vecDisplay );

	return 0;
}


7)合并容器元素 : merge()
类似copy的用法
 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4. #include "vector"  
  5. #include "algorithm"  
  6.   
  7. void vecDisplay( const int iValue )   
  8. {  
  9.     cout << "current container value is: " << iValue << endl;  
  10. }  
  11.   
  12. int _tmain(int argc, _TCHAR* argv[])  
  13. {  
  14.     vector<float> vecScoreFirst;  
  15.     vector<float> vecScoreSecond;  
  16.     vector<float> vecResutl;  
  17.   
  18.     for ( int i = 0; i < 10; i++ )  
  19.     {  
  20.         vecScoreFirst.push_back( 60.0f + i );  
  21.     }  
  22.     cout << "vecScoreFirst current value:" << endl;  
  23.     for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );  
  24.   
  25.     for ( int i = 0; i < 10; i++ )  
  26.     {  
  27.         vecScoreSecond.push_back( 60.0f + i );  
  28.     }  
  29.     cout << "\n" << endl;  
  30.     cout << "vecScoreSecond current value:" << endl;  
  31.     for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );  
  32.   
  33.   
  34.     // used merge the two container must to pass through sort, otherwise error  
  35.     vecResutl.resize( vecScoreFirst.size() + vecScoreSecond.size() );  
  36.     merge( vecScoreFirst.begin(), vecScoreFirst.end(), vecScoreSecond.begin(), vecScoreSecond.end(), vecResutl.begin() );  
  37.   
  38.     cout << "\n" << endl;  
  39.     cout << "vecScore current value:" << endl;  
  40.     for_each( vecResutl.begin(), vecResutl.end(), vecDisplay );  
  41.   
  42.     return 0;  
  43. }  
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "vector"
#include "algorithm"

void vecDisplay( const int iValue ) 
{
	cout << "current container value is: " << iValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<float> vecScoreFirst;
	vector<float> vecScoreSecond;
	vector<float> vecResutl;

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreFirst.push_back( 60.0f + i );
	}
	cout << "vecScoreFirst current value:" << endl;
	for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreSecond.push_back( 60.0f + i );
	}
	cout << "\n" << endl;
	cout << "vecScoreSecond current value:" << endl;
	for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );


	// used merge the two container must to pass through sort, otherwise error
	vecResutl.resize( vecScoreFirst.size() + vecScoreSecond.size() );
	merge( vecScoreFirst.begin(), vecScoreFirst.end(), vecScoreSecond.begin(), vecScoreSecond.end(), vecResutl.begin() );

	cout << "\n" << endl;
	cout << "vecScore current value:" << endl;
	for_each( vecResutl.begin(), vecResutl.end(), vecDisplay );

	return 0;
}

8)set_union()
合并之后去掉两个容器中重复的部分

 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4. #include "vector"  
  5. #include "algorithm"  
  6.   
  7. void vecDisplay( const int iValue )   
  8. {  
  9.     cout << "current container value is: " << iValue << endl;  
  10. }  
  11.   
  12. int _tmain(int argc, _TCHAR* argv[])  
  13. {  
  14.     vector<float> vecScoreFirst;  
  15.     vector<float> vecScoreSecond;  
  16.     vector<float> vecResutl;  
  17.   
  18.     for ( int i = 0; i < 10; i++ )  
  19.     {  
  20.         vecScoreFirst.push_back( 60.0f + i );  
  21.     }  
  22.     cout << "vecScoreFirst current value:" << endl;  
  23.     for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );  
  24.   
  25.     for ( int i = 0; i < 10; i++ )  
  26.     {  
  27.         vecScoreSecond.push_back( 60.0f + i );  
  28.     }  
  29.     cout << "\n" << endl;  
  30.     cout << "vecScoreSecond current value:" << endl;  
  31.     for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );  
  32.   
  33.   
  34.     // used merge the two container must to pass through sort, otherwise error  
  35.     vecResutl.resize( vecScoreFirst.size() + vecScoreSecond.size() );  
  36.     set_union( vecScoreFirst.begin(), vecScoreFirst.end(), vecScoreSecond.begin(), vecScoreSecond.end(), vecResutl.begin() );  
  37.   
  38.     cout << "\n" << endl;  
  39.     cout << "vecScore current value:" << endl;  
  40.     for_each( vecResutl.begin(), vecResutl.end(), vecDisplay );  
  41.   
  42.     return 0;  
  43. }  
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "vector"
#include "algorithm"

void vecDisplay( const int iValue ) 
{
	cout << "current container value is: " << iValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<float> vecScoreFirst;
	vector<float> vecScoreSecond;
	vector<float> vecResutl;

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreFirst.push_back( 60.0f + i );
	}
	cout << "vecScoreFirst current value:" << endl;
	for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreSecond.push_back( 60.0f + i );
	}
	cout << "\n" << endl;
	cout << "vecScoreSecond current value:" << endl;
	for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );


	// used merge the two container must to pass through sort, otherwise error
	vecResutl.resize( vecScoreFirst.size() + vecScoreSecond.size() );
	set_union( vecScoreFirst.begin(), vecScoreFirst.end(), vecScoreSecond.begin(), vecScoreSecond.end(), vecResutl.begin() );

	cout << "\n" << endl;
	cout << "vecScore current value:" << endl;
	for_each( vecResutl.begin(), vecResutl.end(), vecDisplay );

	return 0;
}

9)transform()
在进行元素的复制时,同时对元素进行某些操作
transform有两种使用方式,分别对应的func参数不同

 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4. #include "vector"  
  5. #include "algorithm"  
  6.   
  7. #define ADD_VALUE 10  
  8.   
  9. // used transform the first form  
  10. int firstAddFunc( int iValue )  
  11. {  
  12.     return iValue + ADD_VALUE;  
  13. }  
  14.   
  15. // used transform the first form  
  16. int secondAddFunc( int iLeftValue, int iRightValue )  
  17. {  
  18.     return iLeftValue + iRightValue;  
  19. }  
  20.   
  21. void vecDisplay( int iValue )  
  22. {  
  23.     cout << "current container value is: " << iValue << endl;  
  24. }  
  25.   
  26. int _tmain(int argc, _TCHAR* argv[])  
  27. {  
  28.     vector<float> vecScoreFirst;  
  29.     vector<float> vecScoreSecond;  
  30.     vector<float> vecResutl;  
  31.   
  32.     for ( int i = 0; i < 10; i++ )  
  33.     {  
  34.         vecScoreFirst.push_back( 60.0f + i );  
  35.     }  
  36.     cout << "vecScoreFirst current value:" << endl;  
  37.     for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );  
  38.   
  39.     for ( int i = 0; i < 10; i++ )  
  40.     {  
  41.         vecScoreSecond.push_back( 80.0f + i );  
  42.     }  
  43.     cout << "\n" << endl;  
  44.     cout << "vecScoreSecond current value:" << endl;  
  45.     for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );  
  46.   
  47.     // used transform the first form  
  48.     vecResutl.resize( vecScoreFirst.size() );  
  49.     transform( vecScoreFirst.begin(), vecScoreFirst.end(), vecResutl.begin(), firstAddFunc );  
  50.     cout << "\n" << endl;  
  51.     cout << "transform the first form vecScore current value:" << endl;  
  52.     for_each( vecResutl.begin(), vecResutl.end(), vecDisplay );  
  53.   
  54.     // used transform the second form  
  55.     vecResutl.clear();  
  56.     vecResutl.resize( vecScoreFirst.size() );  
  57.     transform( vecScoreFirst.begin(), vecScoreFirst.end(), vecScoreSecond.begin(), vecResutl.begin(), secondAddFunc );  
  58.     cout << "\n" << endl;  
  59.     cout << "transform the second form vecScore current value:" << endl;  
  60.     for_each( vecResutl.begin(), vecResutl.end(), vecDisplay );  
  61.   
  62.     return 0;  
  63. }  
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "vector"
#include "algorithm"

#define ADD_VALUE 10

// used transform the first form
int firstAddFunc( int iValue )
{
	return iValue + ADD_VALUE;
}

// used transform the first form
int secondAddFunc( int iLeftValue, int iRightValue )
{
	return iLeftValue + iRightValue;
}

void vecDisplay( int iValue )
{
	cout << "current container value is: " << iValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<float> vecScoreFirst;
	vector<float> vecScoreSecond;
	vector<float> vecResutl;

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreFirst.push_back( 60.0f + i );
	}
	cout << "vecScoreFirst current value:" << endl;
	for_each( vecScoreFirst.begin(), vecScoreFirst.end(), vecDisplay );

	for ( int i = 0; i < 10; i++ )
	{
		vecScoreSecond.push_back( 80.0f + i );
	}
	cout << "\n" << endl;
	cout << "vecScoreSecond current value:" << endl;
	for_each( vecScoreSecond.begin(), vecScoreSecond.end(), vecDisplay );

	// used transform the first form
	vecResutl.resize( vecScoreFirst.size() );
	transform( vecScoreFirst.begin(), vecScoreFirst.end(), vecResutl.begin(), firstAddFunc );
	cout << "\n" << endl;
	cout << "transform the first form vecScore current value:" << endl;
	for_each( vecResutl.begin(), vecResutl.end(), vecDisplay );

	// used transform the second form
	vecResutl.clear();
	vecResutl.resize( vecScoreFirst.size() );
	transform( vecScoreFirst.begin(), vecScoreFirst.end(), vecScoreSecond.begin(), vecResutl.begin(), secondAddFunc );
	cout << "\n" << endl;
	cout << "transform the second form vecScore current value:" << endl;
	for_each( vecResutl.begin(), vecResutl.end(), vecDisplay );

	return 0;
}

10)sort()、reverse()
排序和翻转算法

 
  1. #include "stdafx.h"  
  2. #include "string"  
  3. #include "iostream"  
  4. using namespace std;  
  5. #include "vector"  
  6. #include "algorithm"  
  7.   
  8. void vecDisplay( const string iValue )   
  9. {  
  10.     cout << "current container value is: " << iValue << endl;  
  11. }  
  12.   
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.     vector<string> vecStudentName;  
  16.     vector<string>::iterator it;  
  17.     vecStudentName.push_back( "zeng" );  
  18.     vecStudentName.push_back( "zengraoli" );  
  19.     vecStudentName.push_back( "zengRaoli" );  
  20.     vecStudentName.push_back( "test" );  
  21.     vecStudentName.push_back( "125308501" );  
  22.     vecStudentName.push_back( "zengRaoli2" );  
  23.     vecStudentName.push_back( "1zeng" );  
  24.   
  25.     cout << "vecStudentName current value:" << endl;  
  26.     for( it = vecStudentName.begin(); it != vecStudentName.end(); it++ )  
  27.     {  
  28.         cout << "vecScore current value:" << ( *it ) << endl;  
  29.     }  
  30.   
  31.     // used sort algorithm  
  32.     sort( vecStudentName.begin(), vecStudentName.end() );  
  33.     cout << "\n" << endl;  
  34.     cout << "pass sort vecStudentName current value:" << endl;  
  35.     for_each( vecStudentName.begin(), vecStudentName.end(), vecDisplay );  
  36.   
  37.     // used reverse algorithm  
  38.     reverse( vecStudentName.begin(), vecStudentName.end() );  
  39.     cout << "\n" << endl;  
  40.     cout << "pass reverse vecStudentName current value:" << endl;  
  41.     for_each( vecStudentName.begin(), vecStudentName.end(), vecDisplay );  
  42.   
  43.     return 0;  
  44. }  
#include "stdafx.h"
#include "string"
#include "iostream"
using namespace std;
#include "vector"
#include "algorithm"

void vecDisplay( const string iValue ) 
{
	cout << "current container value is: " << iValue << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<string> vecStudentName;
	vector<string>::iterator it;
	vecStudentName.push_back( "zeng" );
	vecStudentName.push_back( "zengraoli" );
	vecStudentName.push_back( "zengRaoli" );
	vecStudentName.push_back( "test" );
	vecStudentName.push_back( "125308501" );
	vecStudentName.push_back( "zengRaoli2" );
	vecStudentName.push_back( "1zeng" );

	cout << "vecStudentName current value:" << endl;
	for( it = vecStudentName.begin(); it != vecStudentName.end(); it++ )
	{
		cout << "vecScore current value:" << ( *it ) << endl;
	}

	// used sort algorithm
	sort( vecStudentName.begin(), vecStudentName.end() );
	cout << "\n" << endl;
	cout << "pass sort vecStudentName current value:" << endl;
	for_each( vecStudentName.begin(), vecStudentName.end(), vecDisplay );

	// used reverse algorithm
	reverse( vecStudentName.begin(), vecStudentName.end() );
	cout << "\n" << endl;
	cout << "pass reverse vecStudentName current value:" << endl;
	for_each( vecStudentName.begin(), vecStudentName.end(), vecDisplay );

	return 0;
}


更改对基本数据类型的sort算法:

 
  1. #include "stdafx.h"  
  2. #include "string"  
  3. #include "vector"  
  4. #include "algorithm"  
  5. #include "assert.h"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9. void vecDisplay( const int iValue )  
  10. {  
  11.     cout << "current value is " << iValue << endl;  
  12. }  
  13.   
  14. // my sort algorithm  
  15. bool defineSort( const int iLeftValue, const int iRightValue )  
  16. {  
  17.     return ( iLeftValue > iRightValue );  
  18. }  
  19.   
  20. int _tmain(int argc, _TCHAR* argv[])  
  21. {  
  22.     vector<int> vecIValue;  
  23.     vecIValue.push_back( 9 );  
  24.     vecIValue.push_back( 1 );  
  25.     vecIValue.push_back( 3 );  
  26.     vecIValue.push_back( 5 );  
  27.     vecIValue.push_back( 8 );  
  28.     vecIValue.push_back( 7 );  
  29.     vecIValue.push_back( 2 );  
  30.   
  31. /* 
  32.     sort( vecIValue.begin(), vecIValue.end() ); 
  33.     cout << "pass sort : " << endl; 
  34.     for_each( vecIValue.begin(), vecIValue.end(), vecDisplay ); 
  35. */  
  36.       
  37.     sort( vecIValue.begin(), vecIValue.end(), defineSort );  
  38.     cout << "pass sort : " << endl;  
  39.     for_each( vecIValue.begin(), vecIValue.end(), vecDisplay );  
  40.   
  41.   
  42.     return 0;  
  43. }  
#include "stdafx.h"
#include "string"
#include "vector"
#include "algorithm"
#include "assert.h"
#include "iostream"
using namespace std;

void vecDisplay( const int iValue )
{
	cout << "current value is " << iValue << endl;
}

// my sort algorithm
bool defineSort( const int iLeftValue, const int iRightValue )
{
	return ( iLeftValue > iRightValue );
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> vecIValue;
	vecIValue.push_back( 9 );
	vecIValue.push_back( 1 );
	vecIValue.push_back( 3 );
	vecIValue.push_back( 5 );
	vecIValue.push_back( 8 );
	vecIValue.push_back( 7 );
	vecIValue.push_back( 2 );

/*
	sort( vecIValue.begin(), vecIValue.end() );
	cout << "pass sort : " << endl;
	for_each( vecIValue.begin(), vecIValue.end(), vecDisplay );
*/
	
	sort( vecIValue.begin(), vecIValue.end(), defineSort );
	cout << "pass sort : " << endl;
	for_each( vecIValue.begin(), vecIValue.end(), vecDisplay );


	return 0;
}

针对于自定义类型的sort算法
需要重写 < 号,暂时类里面不带有指针变量,否则还要重写拷贝构造

 
  1. #include "stdafx.h"  
  2. #include "string"  
  3. #include "vector"  
  4. #include "algorithm"  
  5. #include "assert.h"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9. namespace Zeng  
  10. {  
  11.     class CTest_Rectang  
  12.     {  
  13.     public:  
  14.         CTest_Rectang( int iLong, int iWidth, int iHeight )  
  15.             : m_iLong( iLong ), m_iWidth( iWidth ), m_iHeight( iHeight )  
  16.         {  
  17.         }  
  18.         bool operator < ( const CTest_Rectang& rCTest_Rectang )  
  19.         {  
  20.             assert( rCTest_Rectang.m_iLong );  
  21.             if ( rCTest_Rectang.m_iLong > this->m_iLong )  
  22.             {  
  23.                 return true;  
  24.             }  
  25.             return false;  
  26.         }  
  27.         friend void vecDisplay( const CTest_Rectang& rCTest_Rectang );  
  28.     private:  
  29.         int m_iLong;  
  30.         int m_iWidth;  
  31.         int m_iHeight;  
  32.     };  
  33.     void vecDisplay( const Zeng::CTest_Rectang& rCTest_Rectang )   
  34.     {  
  35.         cout << "current container Zeng::CTest_Rectang m_iLong is: " << rCTest_Rectang.m_iLong << endl;  
  36.     }  
  37. }  
  38.   
  39. int _tmain(int argc, _TCHAR* argv[])  
  40. {  
  41.     vector<Zeng::CTest_Rectang> vecCTestRectang;  
  42.     for ( int i = 0; i < 8; i++ )  
  43.     {  
  44.         vecCTestRectang.push_back( Zeng::CTest_Rectang( 14 + i, 14, 14 ) );  
  45.     }  
  46.   
  47.     // used sort algorithm  
  48.     sort( vecCTestRectang.begin(), vecCTestRectang.end() );  
  49.     cout << "\n" << endl;  
  50.     cout << "pass sort vecStudentName current value:" << endl;  
  51.     for_each( vecCTestRectang.begin(), vecCTestRectang.end(), Zeng::vecDisplay );  
  52.   
  53.     // used reverse algorithm  
  54.     reverse( vecCTestRectang.begin(), vecCTestRectang.end() );  
  55.     cout << "\n" << endl;  
  56.     cout << "pass reverse vecStudentName current value:" << endl;  
  57.     for_each( vecCTestRectang.begin(), vecCTestRectang.end(), Zeng::vecDisplay );  
  58.   
  59.     return 0;  
  60. }  
#include "stdafx.h"
#include "string"
#include "vector"
#include "algorithm"
#include "assert.h"
#include "iostream"
using namespace std;

namespace Zeng
{
	class CTest_Rectang
	{
	public:
		CTest_Rectang( int iLong, int iWidth, int iHeight )
			: m_iLong( iLong ), m_iWidth( iWidth ), m_iHeight( iHeight )
		{
		}
		bool operator < ( const CTest_Rectang& rCTest_Rectang )
		{
			assert( rCTest_Rectang.m_iLong );
			if ( rCTest_Rectang.m_iLong > this->m_iLong )
			{
				return true;
			}
			return false;
		}
		friend void vecDisplay( const CTest_Rectang& rCTest_Rectang );
	private:
		int m_iLong;
		int m_iWidth;
		int m_iHeight;
	};
	void vecDisplay( const Zeng::CTest_Rectang& rCTest_Rectang ) 
	{
		cout << "current container Zeng::CTest_Rectang m_iLong is: " << rCTest_Rectang.m_iLong << endl;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<Zeng::CTest_Rectang> vecCTestRectang;
	for ( int i = 0; i < 8; i++ )
	{
		vecCTestRectang.push_back( Zeng::CTest_Rectang( 14 + i, 14, 14 ) );
	}

	// used sort algorithm
	sort( vecCTestRectang.begin(), vecCTestRectang.end() );
	cout << "\n" << endl;
	cout << "pass sort vecStudentName current value:" << endl;
	for_each( vecCTestRectang.begin(), vecCTestRectang.end(), Zeng::vecDisplay );

	// used reverse algorithm
	reverse( vecCTestRectang.begin(), vecCTestRectang.end() );
	cout << "\n" << endl;
	cout << "pass reverse vecStudentName current value:" << endl;
	for_each( vecCTestRectang.begin(), vecCTestRectang.end(), Zeng::vecDisplay );

	return 0;
}

11)min_element()、max_element()
取最大最小值算法,容器需要经过sort排序
找到后输出后面的全部值

 
  1. #include "stdafx.h"  
  2. #include "string"  
  3. #include "vector"  
  4. #include "algorithm"  
  5. #include "assert.h"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9. void vecDisplay( const int iValue )  
  10. {  
  11.     cout << "current value is " << iValue << endl;  
  12. }  
  13.   
  14. // my sort algorithm  
  15. bool defineSort( const int iLeftValue, const int iRightValue )  
  16. {  
  17.     return ( iLeftValue > iRightValue );  
  18. }  
  19.   
  20. int _tmain(int argc, _TCHAR* argv[])  
  21. {  
  22.     vector<int> vecIValue;  
  23.     vecIValue.push_back( 7 );  
  24.     vecIValue.push_back( 8 );  
  25.     vecIValue.push_back( 3 );  
  26.     vecIValue.push_back( 1 );  
  27.     vecIValue.push_back( 9 );  
  28.     vecIValue.push_back( 5 );  
  29.     vecIValue.push_back( 2 );  
  30.   
  31.     vector<int>::iterator it;  
  32.     it = max_element( vecIValue.begin(), vecIValue.end() );  
  33.     for ( ; it != vecIValue.end(); it++ )  
  34.     {  
  35.         cout << "max_element current value is : " << ( *it ) << endl;  
  36.     }  
  37.   
  38.     cout << "\n" << endl;  
  39.     it = min_element( vecIValue.begin(), vecIValue.end() );  
  40.     for ( ; it != vecIValue.end(); it++ )  
  41.     {  
  42.         cout << "min_element current value is : " << ( *it ) << endl;  
  43.     }  
  44.   
  45.     return 0;  
  46. }  
#include "stdafx.h"
#include "string"
#include "vector"
#include "algorithm"
#include "assert.h"
#include "iostream"
using namespace std;

void vecDisplay( const int iValue )
{
	cout << "current value is " << iValue << endl;
}

// my sort algorithm
bool defineSort( const int iLeftValue, const int iRightValue )
{
	return ( iLeftValue > iRightValue );
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> vecIValue;
	vecIValue.push_back( 7 );
	vecIValue.push_back( 8 );
	vecIValue.push_back( 3 );
	vecIValue.push_back( 1 );
	vecIValue.push_back( 9 );
	vecIValue.push_back( 5 );
	vecIValue.push_back( 2 );

	vector<int>::iterator it;
	it = max_element( vecIValue.begin(), vecIValue.end() );
	for ( ; it != vecIValue.end(); it++ )
	{
		cout << "max_element current value is : " << ( *it ) << endl;
	}

	cout << "\n" << endl;
	it = min_element( vecIValue.begin(), vecIValue.end() );
	for ( ; it != vecIValue.end(); it++ )
	{
		cout << "min_element current value is : " << ( *it ) << endl;
	}

	return 0;
}

函数指针
1)
根据函数指针所指向函数的不同,需要根据函数的具体声明来定义一个函数指针,其语法格式如下:
    函数返回值类型标识符 ( 指针变量名 )( 形参列表 );
由于"()"的优先级高于"*",所以指针变量名外的括号必不可少。形参列表表示指针变量指向的函数所带的参数列表。
2)
例如有一个函数
void PrintPass( int iLeft, int iRightValue );
如果要声明一个函数指针
void ( *pFunc )( int iLeft, int iRightValue );
省略形参后
void ( *pFunc )( int, int );
如果要定义多个同一类型的指针,还可以使用typedef关键字定义一种新的函数之着呢的数据类型,用这种新的数据类型来定义函数指针,例如
// 定义一种新的函数指针的数据类型
typedef bool ( *pFunc )( int, int );
// 使用新的数据类型定义函数指针
pFunc pMax;
// 直接指向函数
pMax = Max;

 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4.   
  5. typedef bool ( *pFunc )( intint );  
  6.   
  7. bool Max( const int iLeftValue, const int iRightValue )  
  8. {  
  9.     return ( iLeftValue > iRightValue );  
  10. }  
  11.   
  12. int _tmain(int argc, _TCHAR* argv[])  
  13. {  
  14.     pFunc pMax;  
  15.     pMax = Max;  
  16.     cout << "pMax( 5, 6 ) this return bool value is : " << pMax( 5, 6 ) << endl;  
  17.     cout << "pMax( 6, 5 ) this return bool value is : " << pMax( 6, 5 ) << endl;  
  18.   
  19.     return 0;  
  20. }  
#include "stdafx.h"
#include "iostream"
using namespace std;

typedef bool ( *pFunc )( int, int );

bool Max( const int iLeftValue, const int iRightValue )
{
	return ( iLeftValue > iRightValue );
}

int _tmain(int argc, _TCHAR* argv[])
{
	pFunc pMax;
	pMax = Max;
	cout << "pMax( 5, 6 ) this return bool value is : " << pMax( 5, 6 ) << endl;
	cout << "pMax( 6, 5 ) this return bool value is : " << pMax( 6, 5 ) << endl;

	return 0;
}

3)
可以在声明的时候不使用typedef直接用auto作为函数指针的数据类型来声明一个函数指针,
auto pMax = Max; // 只能在vs2010上面才使用有效

 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4.   
  5. int Max( const int iLeftValue, const int iRightValue )  
  6. {  
  7.     return ( iLeftValue > iRightValue );  
  8. }  
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     auto pMaxSendcont = Max;  
  13.     cout << "pMaxSendcont( 5, 6 ) this return bool value is : " << pMaxSendcont( 5, 6 ) << endl;  
  14.     cout << "pMaxSendcont( 6, 5 ) this return bool value is : " << pMaxSendcont( 6, 5 ) << endl;  
  15.     return 0;  
  16. }  
#include "stdafx.h"
#include "iostream"
using namespace std;

int Max( const int iLeftValue, const int iRightValue )
{
	return ( iLeftValue > iRightValue );
}

int _tmain(int argc, _TCHAR* argv[])
{
	auto pMaxSendcont = Max;
	cout << "pMaxSendcont( 5, 6 ) this return bool value is : " << pMaxSendcont( 5, 6 ) << endl;
	cout << "pMaxSendcont( 6, 5 ) this return bool value is : " << pMaxSendcont( 6, 5 ) << endl;
	return 0;
}

用函数指针实现回调函数
1)
回调函数就是一个通过函数指针调用的函数。如果吧函数的指针(地址)作为参数传递给另一个函数,当这个指针被用为调用它所指向的函数时,就说这事回调函数。回调函数不是由该函数的实现方直接

调用,而是特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
2)
回调函数实现的机制是:
a、定义一个回调函数
b、提供函数实现的一方在初始化的时候,将回调函数的函数指针注册给调用者
c、当特定的事件或条件发生的时候,调用者使用函数指针调用回调函数对事件进行处理
3)为什么要使用回调函数
因为可以把调用者与被调用者分开,所以调用者不关心谁是被调用者。它只需知道存在一个具有特定原型和限制条件的被调用函数

 
  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4.   
  5. typedef bool ( *PMAXFUNC )( intint );  
  6.   
  7. void PrintMessage( int iLeftValue, int iRightValue, PMAXFUNC pMax )  
  8. {  
  9.     cout << "Print Header :" << endl;  
  10.     cout << "====================================================" << endl;  
  11.     cout << "pMax LeftValue is : " << iLeftValue << endl;  
  12.     cout << "pMax RightValue is : " << iRightValue << endl;  
  13.     cout << "pMax function return is : " << pMax( iLeftValue, iRightValue ) << endl;  
  14.     cout << "====================================================" << endl;  
  15.     cout << "Print ender :" << endl;  
  16. }  
  17.   
  18. bool Max( const int iLeftValue, const int iRightValue )  
  19. {  
  20.     return ( iLeftValue > iRightValue );  
  21. }  
  22.   
  23. int _tmain(int argc, _TCHAR* argv[])  
  24. {  
  25.     PMAXFUNC pMax = Max;  
  26.     PrintMessage( 5, 6, pMax );  
  27.   
  28.     return 0;  
  29. }  
#include "stdafx.h"
#include "iostream"
using namespace std;

typedef bool ( *PMAXFUNC )( int, int );

void PrintMessage( int iLeftValue, int iRightValue, PMAXFUNC pMax )
{
	cout << "Print Header :" << endl;
	cout << "====================================================" << endl;
	cout << "pMax LeftValue is : " << iLeftValue << endl;
	cout << "pMax RightValue is : " << iRightValue << endl;
	cout << "pMax function return is : " << pMax( iLeftValue, iRightValue ) << endl;
	cout << "====================================================" << endl;
	cout << "Print ender :" << endl;
}

bool Max( const int iLeftValue, const int iRightValue )
{
	return ( iLeftValue > iRightValue );
}

int _tmain(int argc, _TCHAR* argv[])
{
	PMAXFUNC pMax = Max;
	PrintMessage( 5, 6, pMax );

	return 0;
}

4)将函数指针应用到STL算法中
ptr_fun()函数将一个普通函数指针转换为一个函数对象
bind1st()函数将整个函数对象的第一个参数绑定为nStandardHeigth

a、在count_if()算法中实现规则和统计标准的完全自定义:

 
  1. #include "stdafx.h"  
  2. #include "vector"  
  3. #include "string"  
  4. #include "algorithm"  
  5. #include "functional"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9. #define STANDARHEIGHT   165  
  10. #define STUDENTNUM      5  
  11.   
  12. class CStudent  
  13. {  
  14. public:  
  15.     CStudent( int iHeight ) : m_iHeight( iHeight )  
  16.     {  
  17.     }  
  18.     int GetHeight() const  
  19.     {  
  20.         return m_iHeight;  
  21.     }  
  22. private:  
  23.     int m_iHeight;  
  24. };  
  25.   
  26. bool countHeight( int iHeight, const CStudent st)  
  27. {  
  28.     return st.GetHeight() > iHeight;  
  29. }  
  30.   
  31. int _tmain(int argc, _TCHAR* argv[])  
  32. {  
  33.     vector<CStudent> vecStudent;  
  34.     for (int i = 0; i < STUDENTNUM; i++)  
  35.     {  
  36.         vecStudent.push_back( CStudent( STANDARHEIGHT - 10 + i * 10 ) );  
  37.     }  
  38.   
  39.     const int nStandarHeight = STANDARHEIGHT;  
  40.     int iCount = count_if( vecStudent.begin(), vecStudent.end(), bind1st( ptr_fun( countHeight ), nStandarHeight ) );  
  41.   
  42.     cout << "the student height greater than Standar Number is : " << iCount << endl;  
  43.   
  44.     return 0;  
  45. }  
#include "stdafx.h"
#include "vector"
#include "string"
#include "algorithm"
#include "functional"
#include "iostream"
using namespace std;

#define STANDARHEIGHT	165
#define STUDENTNUM		5

class CStudent
{
public:
	CStudent( int iHeight ) : m_iHeight( iHeight )
	{
	}
	int GetHeight() const
	{
		return m_iHeight;
	}
private:
	int m_iHeight;
};

bool countHeight( int iHeight, const CStudent st)
{
	return st.GetHeight() > iHeight;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<CStudent> vecStudent;
	for (int i = 0; i < STUDENTNUM; i++)
	{
		vecStudent.push_back( CStudent( STANDARHEIGHT - 10 + i * 10 ) );
	}

	const int nStandarHeight = STANDARHEIGHT;
	int iCount = count_if( vecStudent.begin(), vecStudent.end(), bind1st( ptr_fun( countHeight ), nStandarHeight ) );

	cout << "the student height greater than Standar Number is : " << iCount << endl;

	return 0;
}

    bind1st()函数将整个函数对象的第一个参数绑定为nStandardHeigth,而函数对象的第二个参数就是iron国企中的CStudent对象作为参数调用countHeight()这个重新定义的统计规则函数,以实现

统计规则和统计标准的完全自定义。

b、在算法中使用指向某个类的成员函数的函数指针

 
  1. #include "stdafx.h"  
  2. #include "vector"  
  3. #include "string"  
  4. #include "algorithm"  
  5. #include "functional"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9. class CStudent  
  10. {  
  11. public:  
  12.     CStudent( string strName )  
  13.     {  
  14.         m_strName = strName;  
  15.     }  
  16.     bool isNamed( string strName )  
  17.     {  
  18.         return strName == m_strName;  
  19.     }  
  20. private:  
  21.     string m_strName;  
  22. };  
  23.   
  24.   
  25. int _tmain(int argc, _TCHAR* argv[])  
  26. {  
  27.     vector<CStudent> vecStudent;  
  28.     vecStudent.push_back( CStudent( "zengraoli1" ) );  
  29.     vecStudent.push_back( CStudent( "zengraoli2" ) );  
  30.     vecStudent.push_back( CStudent( "zengraoli3" ) );  
  31.       
  32.     string strFindName = "zengraoli2";  
  33.     vector<CStudent>::iterator it = find_if( vecStudent.begin(), vecStudent.end(),  
  34.                                              bind2nd( mem_fun_ref( &CStudent::isNamed ), strFindName ) );  
  35.     if ( it != vecStudent.end() )  
  36.     {  
  37.         cout << "找到了对应的vecStudent!" << endl;  
  38.     }  
  39.   
  40.     return 0;  
  41. }  
#include "stdafx.h"
#include "vector"
#include "string"
#include "algorithm"
#include "functional"
#include "iostream"
using namespace std;

class CStudent
{
public:
	CStudent( string strName )
	{
		m_strName = strName;
	}
	bool isNamed( string strName )
	{
		return strName == m_strName;
	}
private:
	string m_strName;
};


int _tmain(int argc, _TCHAR* argv[])
{
	vector<CStudent> vecStudent;
	vecStudent.push_back( CStudent( "zengraoli1" ) );
	vecStudent.push_back( CStudent( "zengraoli2" ) );
	vecStudent.push_back( CStudent( "zengraoli3" ) );
	
	string strFindName = "zengraoli2";
	vector<CStudent>::iterator it = find_if( vecStudent.begin(), vecStudent.end(),
											 bind2nd( mem_fun_ref( &CStudent::isNamed ), strFindName ) );
	if ( it != vecStudent.end() )
	{
		cout << "找到了对应的vecStudent!" << endl;
	}

	return 0;
}

    在这段代码中,&CStudent::isNamed去的成员函数isNamed()的地址,也就是获得了指向这个成员函数的函数指针;然后使用mem_fun_ref()函数将这个函数指针构造成一个函数对象,如果容器中保存的是指向对象的指针,就应该使用mem_fun_ref()函数来完成这一任务。
    因为这个成员函数需要一个蚕食,所以更进一步的,使用bind2nd()函数绑定其第二个参数strFindName来作为查找条件。因为这是一个类的成员函数指针,所以容器中的对象会作为默认隐含的第一个参数。

=====================================================================
函数指针配合STL算法的应用,将STL算法的通用性发挥到了极致。


函数对象
1)所谓函数对象,就是定义了函数调用操作符(function-call operator),即operator()的普通类的对象。在重载的函数调用操作符中,可以实现函数的所有功能。同事,因为类具有属性,可以将每次

函数调用的状态数据保存到他的属性中,这样函数对象就不会像函数指针那样失忆了,从而可以应用在更广的范围内。
2)定义一个模板函数对象
------------------------------------------------------

 
  1. template <typename T>  
  2. class myMax  
  3. {  
  4.     T operator()(T a, T b)  
  5.     {  
  6.         return ( a > b ? a : b );  
  7.     }  
  8. };  
template <typename T>
class myMax
{
	T operator()(T a, T b)
	{
		return ( a > b ? a : b );
	}
};

3)在STL中使用函数对象
------------------------------------------------------

 
  1. #include "stdafx.h"  
  2. #include "vector"  
  3. #include "algorithm"  
  4. #include "iostream"  
  5. using namespace std;  
  6.   
  7. namespace Zeng  
  8. {  
  9.     class CStudent  
  10.     {  
  11.     public:  
  12.         CStudent( int nHeight ) : m_nHieght( nHeight )   
  13.         {  
  14.         }  
  15.         int GetHeight()  
  16.         {  
  17.             return m_nHieght;  
  18.         }  
  19.     private:  
  20.         int m_nHieght;  
  21.     };  
  22.   
  23.     class CAverageHeight  
  24.     {  
  25.     public:  
  26.         CAverageHeight() : m_nCount( 0 ), m_nTotalHeight( 0 )  
  27.         {  
  28.         }  
  29.         void operator ()( CStudent st )  
  30.         {  
  31.             m_nTotalHeight += st.GetHeight();  
  32.             m_nCount++;  
  33.         }  
  34.         int GetCount()  
  35.         {  
  36.             return m_nCount;  
  37.         }  
  38.         int GetTotalHeight()  
  39.         {  
  40.             return m_nTotalHeight;  
  41.         }  
  42.         float GetAverageHeight()  
  43.         {  
  44.             if ( 0 != m_nCount )  
  45.             {  
  46.                 return static_cast<float>( GetTotalHeight() / GetCount() );  
  47.             }  
  48.             return 0;  
  49.         }  
  50.     private:  
  51.         int m_nCount;  
  52.         int m_nTotalHeight;  
  53.     };  
  54. }  
  55.   
  56.   
  57. int _tmain(int argc, _TCHAR* argv[])  
  58. {  
  59.     vector<Zeng::CStudent> vecStudent;  
  60.     vecStudent.push_back( Zeng::CStudent( 155 ) );  
  61.     vecStudent.push_back( Zeng::CStudent( 165 ) );  
  62.     vecStudent.push_back( Zeng::CStudent( 175 ) );  
  63.     vecStudent.push_back( Zeng::CStudent( 185 ) );  
  64.     vecStudent.push_back( Zeng::CStudent( 195 ) );  
  65.   
  66.     // use function object  
  67.     Zeng::CAverageHeight ah;  
  68.     // use function object in the stl algorithm  
  69.     ah = for_each( vecStudent.begin(), vecStudent.end(), ah);  
  70.     cout << "average height is : " << ah.GetAverageHeight() << endl;  
  71.     cout << "the student count is : " << ah.GetCount() << endl;  
  72.   
  73.     return 0;  
  74. }  
#include "stdafx.h"
#include "vector"
#include "algorithm"
#include "iostream"
using namespace std;

namespace Zeng
{
	class CStudent
	{
	public:
		CStudent( int nHeight ) : m_nHieght( nHeight ) 
		{
		}
		int GetHeight()
		{
			return m_nHieght;
		}
	private:
		int m_nHieght;
	};

	class CAverageHeight
	{
	public:
		CAverageHeight() : m_nCount( 0 ), m_nTotalHeight( 0 )
		{
		}
		void operator ()( CStudent st )
		{
			m_nTotalHeight += st.GetHeight();
			m_nCount++;
		}
		int GetCount()
		{
			return m_nCount;
		}
		int GetTotalHeight()
		{
			return m_nTotalHeight;
		}
		float GetAverageHeight()
		{
			if ( 0 != m_nCount )
			{
				return static_cast<float>( GetTotalHeight() / GetCount() );
			}
			return 0;
		}
	private:
		int m_nCount;
		int m_nTotalHeight;
	};
}


int _tmain(int argc, _TCHAR* argv[])
{
	vector<Zeng::CStudent> vecStudent;
	vecStudent.push_back( Zeng::CStudent( 155 ) );
	vecStudent.push_back( Zeng::CStudent( 165 ) );
	vecStudent.push_back( Zeng::CStudent( 175 ) );
	vecStudent.push_back( Zeng::CStudent( 185 ) );
	vecStudent.push_back( Zeng::CStudent( 195 ) );

	// use function object
	Zeng::CAverageHeight ah;
	// use function object in the stl algorithm
	ah = for_each( vecStudent.begin(), vecStudent.end(), ah);
	cout << "average height is : " << ah.GetAverageHeight() << endl;
	cout << "the student count is : " << ah.GetCount() << endl;

	return 0;
}

说明:在这里创建了一个函数对象ah并将它应用到for_each()算法中,for_each()算法会以容器中的每个Student对象为参数来对这个函数对象的"()"操作符进行调用。这时,函数对象自然就会将每个

Student对象的身高累加到它自己的m_nTotalHeight属性上,同事它还会记录已经统计过的对象数目。最后,for_each()算法会将完成统计后的函数对象作为结果返回,而这时的函数对象ah已经是一个保存了统计结果的函数对象了。通过函数对象提供的接口函数,可以轻松地获得统计结果并进行输出。


还可以这么用:

 
  1. #include "stdafx.h"  
  2. #include "vector"  
  3. #include "algorithm"  
  4. #include "iostream"  
  5. using namespace std;  
  6.   
  7. namespace Zeng  
  8. {  
  9.     class CStudent  
  10.     {  
  11.     public:  
  12.         CStudent( int nHeight ) : m_nHieght( nHeight )   
  13.         {  
  14.         }  
  15.         int GetHeight()  
  16.         {  
  17.             return m_nHieght;  
  18.         }  
  19.     private:  
  20.         int m_nHieght;  
  21.     };  
  22.   
  23.     class CAverageHeight  
  24.     {  
  25.     public:  
  26.         CAverageHeight() : m_nCount( 0 ), m_nTotalHeight( 0 )  
  27.         {  
  28.         }  
  29.         void operator ()( CStudent st )  
  30.         {  
  31.             m_nTotalHeight += st.GetHeight();  
  32.             m_nCount++;  
  33.         }  
  34.         operator float()  
  35.         {  
  36.             return GetAverageHeight();  
  37.         }  
  38.         operator int()  
  39.         {  
  40.             return GetCount();  
  41.         }  
  42.         int GetCount()  
  43.         {  
  44.             return m_nCount;  
  45.         }  
  46.         int GetTotalHeight()  
  47.         {  
  48.             return m_nTotalHeight;  
  49.         }  
  50.         float GetAverageHeight()  
  51.         {  
  52.             if ( 0 != m_nCount )  
  53.             {  
  54.                 return static_cast<float>( GetTotalHeight() / GetCount() );  
  55.             }  
  56.             return 0;  
  57.         }  
  58.     private:  
  59.         int m_nCount;  
  60.         int m_nTotalHeight;  
  61.     };  
  62. }  
  63.   
  64.   
  65. int _tmain(int argc, _TCHAR* argv[])  
  66. {  
  67.     vector<Zeng::CStudent> vecStudent;  
  68.     vecStudent.push_back( Zeng::CStudent( 155 ) );  
  69.     vecStudent.push_back( Zeng::CStudent( 165 ) );  
  70.     vecStudent.push_back( Zeng::CStudent( 175 ) );  
  71.     vecStudent.push_back( Zeng::CStudent( 185 ) );  
  72.     vecStudent.push_back( Zeng::CStudent( 195 ) );  
  73.   
  74.     // use function object  
  75.     float fAverHeight = for_each( vecStudent.begin(), vecStudent.end(), Zeng::CAverageHeight() );  
  76.     cout << "average height is : " << fAverHeight << endl;  
  77.     int iCount = for_each( vecStudent.begin(), vecStudent.end(), Zeng::CAverageHeight() );  
  78.     cout << "average height is : " << iCount << endl;  
  79.     return 0;  


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值