essential C++的复习

1. 对vector的简单介绍.

程序的主要功能是:从六个随机序列中选取一个序列,随机读取两个数,让用户猜测第三个数.最多猜五次,判断猜对的概率:

#include <iostream>
#include <vector>
#include <stdlib.h>
#include <string>
#include <time.h>
using namespace std;

const int SIZE = 8;

/* 从随机的序列ivvec中提取出连续的三个数*/
void getNum( vector< vector< int > > &ivvec, int &firstNum, int &secondNum, int &thirdNum );
/* 对六个基本的序列进行初始化*/
void initList( vector< vector< int > > &ivvec );
/*对随机产生的序列和数进行猜测游戏*/
void guessNum( vector< vector< int > > &ivvec );

int main( void )
{
	vector< vector< int > > ivvec;
	int			firstNum = 0;
	int			secondNum = 0;
	int			thirdNum = 0;

	initList( ivvec );
	getNum( ivvec, firstNum, secondNum, thirdNum );
	guessNum( ivvec );

	return 0;
}

void initList( vector< vector< int > > &ivvec )
{
	int			arrFib[ SIZE ] = {1, 1, 2, 3, 5, 8, 13, 21};
	int			arrLuc[ SIZE] = {1, 3, 4, 7, 11, 18, 29, 47};
	int			arrPel[ SIZE ] = {1, 2, 5, 12, 29, 70, 169, 408};
	int			arrTri[ SIZE ] = {1, 3, 6, 10, 15, 21, 28, 36};
	int			arrSqu[ SIZE ] = {1, 4, 9, 16, 25, 36, 49, 64};
	int			arrPen[ SIZE ] = {1, 5, 12, 22, 35, 51, 70, 92};
	vector<int>		iFibVec(arrFib, arrFib + SIZE );
	vector<int>		iLucVec(arrLuc, arrLuc + SIZE );
	vector<int>		iPelVec(arrPel, arrPel + SIZE );
	vector<int>		iTriVec(arrTri, arrTri + SIZE );
	vector<int>		iSquVec(arrSqu, arrSqu + SIZE );
	vector<int>		iPenVec(arrPen, arrPen + SIZE );

	ivvec.push_back( iFibVec );
	ivvec.push_back( iLucVec );
	ivvec.push_back( iPelVec );
	ivvec.push_back( iTriVec );
	ivvec.push_back( iSquVec );
	ivvec.push_back( iPenVec );
}

void getNum( vector< vector< int > > &ivvec, int &firstNum, int &secondNum, int &thirdNum )
{
	int			randomSeq = 0;
	int			randomBegin = 0;

	srand( ( unsigned int )time( NULL ) );
	randomSeq = rand() % ( SIZE - 2 );
	randomBegin = rand() % ( SIZE - 2 );

	firstNum = ivvec[ randomSeq ][ randomBegin ];
	secondNum = ivvec[ randomSeq ][ randomBegin + 1 ];
	thirdNum = ivvec[ randomSeq ][ randomBegin + 2 ];
}

void guessNum( vector< vector< int > > &ivvec )
{
	bool		bTry = true;		//用户想再尝试一次
	const int	maxTries = 5;		//最多尝试5次
	int		numTries = 0;		//用户尝试的次数
	int		numRight = 0;		//用户正确的次数

	while ( bTry ){
		int		firstNum = 0;
		int		secondNum = 0;
		int		thirdNum = 0;
		string		userChoise;

		if ( numTries >= maxTries ){
			cout << "sorry, you have tried max times." << endl;
			break;
		}
		getNum( ivvec, firstNum, secondNum, thirdNum );
		cout << "the first number is : " << firstNum << "\nand the second number is: " << secondNum << endl;
		cout << "please enter the third number:";
		int			userNum = 0;
		cin >> userNum;

		if ( userNum == thirdNum ){
			numRight++;
			numTries++;
			cout << "you are right. do you want to try another numbers?(N/n to break, another continue)" << endl;
			cin >> userChoise;
		}
		else{
			numTries++;
			cout << "you are wrong. do you want to try another numbers?(N/n to break, another continue)" << endl;
			cin >> userChoise;
		}

		if ( ( "n" == userChoise ) || ( "N" == userChoise ) ){
			break;
		}
	}

	cout << "the rate success is:" << ( numRight * 1.0 / numTries ) * 100 << "%" << endl;
}
程序输出:



2. 函数的调用

1) 举例说明如何调用函数,提供默认参数.以下程序详细的介绍了冒泡排序法的始末:

#include <iostream>
#include <vector>
#include <fstream>
#include <time.h>
using namespace std;

/* 交换两个数,并且将交换输出到ofil中去*/
void swap( int *px, int *py, ofstream *ofil = 0 );
/* 冒泡排序法,并且将每次的冒泡操作均记录到ofil中去*/
template< typename T >
void bubbleSort( vector< int > &ivec, T *ofil = 0 );
/* 打印容器*/
void display( vector< int > ivec, ostream &os = cout );

int main( void )
{
	vector< int > ivec;
	
	srand( ( unsigned int )time( NULL ) );
	for ( int i = 0; i < 8; i++ ){
		ivec.push_back( rand() % 100 );
	}

	cout << "before sort:" << endl;
	display( ivec );
	bubbleSort< ostream >( ivec, &cout );
	cout << "after sort:" << endl;
	display( ivec, cout );
}

void swap( int *px, int *py, ofstream *ofil )
{
	int temp = *px; 
	*px = *py;
	*py = temp;
	if ( 0 != ofil ){
		( *ofil ) << "swap " << *py << " and " << *px << endl; 
	}
}

template< typename T >
void bubbleSort( vector< int > &ivec, T *ofil )
{
	for ( int ix = 0; ix < ivec.size() - 1; ix++ ){
		for (int iy = ix + 1; iy < ivec.size(); iy++ ){
			if ( ivec[ ix ] > ivec[ iy ] ){
				if ( 0 != ofil ){
					( *ofil ) << "about to call swap! ix:" << ix << " iy:" << iy << "\tswaping:" << ivec[ ix ] << " with " << ivec[ iy ] << endl;
				}
				swap( &ivec[ ix ], &ivec[ iy ] );
			}
		}
	}
}

void display( vector< int > ivec, ostream &os )
{
	for ( int ix = 0; ix < ivec.size(); ix++ ){
		os << ivec[ ix ] << " ";
	}

	os << endl;
}

程序输出:



对这个程序,有以下几点需要注意下:

1---- 默认参数通常在声明中出现,而在定义中不出现(声明的作用就是为了定义函数的原型,但是不定义其内容)

2----这里用到了模板的技术,所以会有如下的函数调用:

bubbleSort< ostream >( ivec, &cout );
3----默认参数ofil均声明为指针而不是其他引用等,是因为只有指针才能与null(或者0)进行判断.而且存在空指针,但是不存在空引用(指针是C/C++强大的地方,要慎用)


2) 使用局部静态对象

#include <iostream>
#include <vector>
using namespace std;

vector< int > fibonSeq( int size );

int main( void )
{
	vector< int > ivec;

	ivec = fibonSeq( 10 );
	ivec = fibonSeq( 5 );
	for ( int ix = 0; ix < ivec.size(); ix++ ){
		cout << ivec[ ix ] << " ";
	}
	cout << endl;

	return 0;
}

vector< int > fibonSeq( int size )
{
	static vector< int > elems;

	for ( int ix = elems.size(); ix < size; ix++ ){
		if ( ( 0 == ix ) || ( 1 == ix ) ){
			elems.push_back( 1 );
		}
		else{
			elems.push_back( elems[ ix - 1] + elems[ ix - 2] ) ;
		}
	}

	return elems;
}

程序输出:



3) 函数指针的使用,增加灵活性

#include <iostream>
#include <vector>
#include <string>
using namespace  std;

void fun1( int iValue )
{
	cout << iValue << endl;
}

void fun2( float fValue )
{
	cout << fValue << endl;
}

void fun3( string sValue )
{
	cout << sValue << endl;
}

template< typename funcType >
void fun( void ( *subFunc )( funcType ), funcType val )
{
	( *subFunc )( val );
}

int main( void )
{
	fun< int >( fun1, 12 );
	fun< float >( fun2, 12.34 );
	fun< string >( fun3, "hello world" );

	return 0;
}

如果这里不考虑指针,我们可以用模板更容易写出来:

#include <iostream>
#include <string>
using namespace std;

template< typename T >
void fun( T TValue)
{
	cout << TValue << endl;
}

int main( void )
{
	fun< int >( 12 );
	fun< float >( 12.34 );
	fun< string >( "hello world" );

	return 0;
}

程序输出:



3. 泛型算法的设计和实现

我们从一个数组从提取出小于10的所有的数,设计一个泛型算法来实现

#include <iostream>
#include <vector>
#include <time.h>
using namespace  std;

template< typename T >
bool lessThan( T val, T maxValue )
{
	return ( val < maxValue );
}

template< typename IteratorType, typename T >
vector< T > lessThan10( IteratorType first, IteratorType last, bool ( *func )( T, T ), T maxValue )
{
	vector< T > Tvec;
	for ( ; first < last; first++ ){
		if ( func( *first, maxValue ) ){
			Tvec.push_back( *first );
		}
	}

	return Tvec;
}

int main( void )
{
	vector< int > ivec;

	srand( ( unsigned int )time( NULL ) );
	for ( int ix = 0; ix < 20; ix++ ){
		ivec.push_back( rand() % 20 );
	}
	for ( int ix = 0; ix < 20; ix++ ){
		cout << ivec[ ix ] << " ";
	}
	cout << endl;

	ivec = lessThan10< vector< int >::iterator, int >( ivec.begin(), ivec.end(), lessThan, 10 );
	for ( int ix = 0; ix < ivec.size(); ix++ ){
		cout << ivec[ ix ] << " ";
	}
	cout << endl;

	return 0;
}

程序输出:


书上提供了一个更好的方法(用到了仿函数,函数适配器等技术)

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
#include <time.h>
using namespace std;

template< typename InputIterator, typename OutputIterator, typename ElemType, typename Comp >
OutputIterator
filter( InputIterator first, InputIterator last, OutputIterator at, const ElemType val, Comp pred )
{
	while ( ( first = find_if( first, last, bind2nd( pred, val ) ) ) != last ){
		cout << " found value:" << *first << endl;
		*at++ = *first++;
	}

	return at;
}

int main( void )
{
	vector< int > ivec;
	vector< int > ivec2;

	srand( ( unsigned int )time( NULL ) );
	for ( int ix = 0; ix < 20; ix++ ){
		ivec.push_back( rand() % 20 );
	}

	filter( ivec.begin(), ivec.end(), back_inserter( ivec2 ), 10, less< int >() );

	for ( int ix = 0; ix < ivec2.size(); ix++ ){
		cout << ivec2[ ix ] << " ";
	}
	cout << endl;

	return 0;
}

程序输出:


那年,当我疯狂爱上C++的时候,我遇见了她:

#include <iostream>
#include <iterator>
#include <string>
using namespace std;

int main(void)
{
	copy(istream_iterator<string>(cin), istream_iterator<string>(), ostream_iterator<string>(cout, " "));

	return 0;
}

4. 实现一个class

1)简单的 stack的实现

stack.h:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

template< typename T >
class Stack{
public:
	bool			push( const T );
	bool			pop( T &elem );
	bool			peek( T &elem );

	bool			empty( void );
	bool			full( void );

	bool			find( T elem );
	int			count( T elem );

	int			size(){
		return _stack.size();
	}

private:
	vector< T >		_stack;
};

stack.cpp:

#include "stack.h"

template< typename T >
inline bool Stack< T >::empty( void )
{
	return _stack.empty();
}

template< typename T >
inline bool Stack< T >::full( void )
{
	return _stack.size() == _stack.max_size();
}

template< typename T >
bool Stack< T >::push( const T elem )
{
	if ( full() ){
		printf("the stack is full\n");
		return false;
	}

	_stack.push_back( elem );

	return true;
}

template< typename T >
bool Stack< T >::pop( T &elem )
{
	if ( empty() ){
		printf("\nthe stack is empty\n");
		return false;
	}

	elem = _stack.back();
	_stack.pop_back();

	return true;
}

template< typename T >
bool Stack< T >::peek( T &elem )
{
	if ( empty() ){
		printf("\nthe stack is empty\n");
		return false;
	}

	elem = _stack.back();

	return true;
}

template< typename T >
bool Stack< T >::find( T elem )
{
	return ::find( _stack.begin(), _stack.end(), elem ) != _stack.end();
}

template< typename T >
int Stack< T >::count( T elem )
{
	return ::count( _stack.begin(), _stack.end(), elem );
}
main.cpp:

#include "stack.cpp"
#include <time.h>

int main( void )
{
	Stack< int > stack;
	int elem;
	
	srand( ( unsigned int )time( NULL ) );
	for ( int ix = 0; ix < 5; ix++ ){
		stack.push( rand() % 20 );
	}
	for ( int ix = 0; ix < 7; ix++ ){
		if ( stack.pop( elem ) ){
			printf("%d ", elem );
		}
	}

	return 0;
}

程序输出:



2) 简单的仿函数

#include <iostream>
#include <vector>
using namespace  std;

template< typename T >
class LessThan{
public:
	LessThan( T val ) : _val( val ){}
	T comp_val() const { return _val; }
	void comp_val( T nval ) { _val = nval; }

	bool operator()( T value ) const{
		return value < _val;
	}
private:
	T			_val;
};

template< typename T >
int count_less_than( const vector< T > vec, T comp )
{
	LessThan< T > lt( comp );

	int		count = 0;
	for ( int ix = 0; ix < vec.size(); ix++ ){
		if ( lt( vec[ ix ] ) ){		//这里的()相当于函数调用,调用了operator
			++count;
		}
	}

	return count;
}

int main( void )
{
	vector< int > ivec;
	for ( int ix = 0; ix < 30; ix++ ){
		ivec.push_back( ix );
	}

	cout << count_less_than< int >( ivec, 10 ) << endl;

	return 0;
}

函数输出:


3) 迭代器的设计

tt.h:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Triangular_iterator{
public:
	Triangular_iterator(int index) : _index(index - 1){}
	bool operator==(const Triangular_iterator&) const;
	bool operator!=(const Triangular_iterator&) const;
	int operator*() const;
	Triangular_iterator& operator++();
	Triangular_iterator operator++(int);
private:
	void check_integrity() const;
	int _index;
};

class Triangular{
	friend Triangular_iterator;
public:
	Triangular( int length = 1, int beg_pos = 1)
	{
		_length = length;
		_beg_pos = beg_pos;
		_elems.clear();		
		//这里进行了一次折中的运算。因为iterator要求_elems必须为static,
		//但是static的性质导致_elems的值每次都在原基础上增加,所以进行clear操作
		for (int i = beg_pos; i < beg_pos + length; i++)
		{
			_elems.push_back(i * (i + 1) / 2);
		}
	}

	typedef Triangular_iterator iterator;

	Triangular_iterator begin() 
	{
		return Triangular_iterator(1);		//这里进行了特殊的修改,为了符合我自己编写代码的习惯,符合_elems为static并且每次都变的情况。
	}

	Triangular_iterator end() 
	{
		return Triangular_iterator(1 + _length);
	}

	int beg_pos() const
	{
		return _beg_pos;
	}
	int length() const
	{
		return _length;
	}
	static void show() 
	{
		for (int i = 0; i < _elems.size(); i++)
		{
			cout << _elems[i] << " ";
		}
	}
	static int sum()
	{
		int sum = 0;
		for (int i = 0; i < _elems.size(); i++)
		{
			sum += _elems[i];
		}

		return sum;
	}
	static void gen_elements(int index)
	{
		for (int i = _elems.size(); i < index; i++)
		{
			_elems.push_back(i * (i + 1) / 2);
		}
	}

private:
	int		_length;
	int		_beg_pos;

	static vector<int>	_elems;
};
vector<int> Triangular::_elems;

ostream& operator<<(ostream &os, Triangular &rhs)
{
	os << "( " << rhs.beg_pos() << " , " << rhs.length() << " ) ";
	rhs.show();

	return os;
}

inline bool Triangular_iterator::operator==(const Triangular_iterator &rhs) const
{
	return _index == rhs._index;
}

inline bool Triangular_iterator::operator!=(const Triangular_iterator &rhs) const
{
	return !(*this == rhs);
}

inline int Triangular_iterator::operator*() const
{
	check_integrity();
	return Triangular::_elems[_index];
}

inline void Triangular_iterator::check_integrity() const
{
	if (_index >= Triangular::_elems.size())
	{
		Triangular::gen_elements(_index + 1);
	}
}

inline Triangular_iterator& Triangular_iterator::operator++()
{
	++_index;
	check_integrity();
	return *this;
}

inline Triangular_iterator Triangular_iterator::operator++(int)
{
	Triangular_iterator tmp = *this;
	++_index;
	check_integrity();
	return tmp;
}

main.cpp:

#include "tt.h"

int main(void)
{
	Triangular tr(32);
	cout << tr << "--sum of elements:" << tr.sum() << endl;

	Triangular tr2(4, 3);
	cout << tr2 << "--sum of elements:" << tr2.sum() << endl;

	Triangular tr3(4, 8);
	cout << tr3 << "--sum of elements:" << tr3.sum() << endl;

	Triangular tr4(20, 12);
	Triangular::iterator it = tr4.begin();
	Triangular::iterator end_it = tr4.end();
	cout << "triangular series of " << tr4.length() << " elements\n";
	cout << tr4 << endl;
	while (it != end_it)
	{
		cout << *it << " ";
		++it;
	}

	cout << endl;

	return 0;
}

程序输出:


这部分知识有点难度,所以要深入去思考理解.


5. 面向对象编程风格

1) 一个简单的面向对象程序

#include <iostream>
#include <string>

using namespace std;

class LibMat{
public:
	LibMat()
	{
		cout << "LibMat::Libmat() default constructor!\n";
	}
	virtual ~LibMat()
	{
		cout << "LibMat::~LibMat() default destructor!\n";
	}
	virtual void print() const
	{
		cout << "LibMat::print() -- I am a LibMat object!\n";
	}
};

class Book : public LibMat{
public:
	Book(const string &title, const string &author)
		:_title(title), _author(author)
	{
		cout << "Book::Book( " << _title << " , "
			<< _author << " ) constructor\n";
	}
	virtual ~Book()
	{
		cout << "Book::~Book() destructor!\n";
	}
	virtual void print() const
	{
		cout << "Book::print() -- I am a Book object!\n"
			<< "My title is: " << _title << "\n"
			<< "My author is: " << _author << endl;
	}
	const string &title() const
	{
		return _title;
	}
	const string &author() const
	{
		return _author;
	}
protected:
	string _title;
	string _author;
};

class AudioBook : public Book{
public:
	AudioBook( const string &title,
		const string &author, const string &narrator)
		:Book(title, author),
		_narrator(narrator)
	{
		cout << "audiobook:audiobook( " << _title
			<< " , " << _author
			<< " ," << _narrator
			<< " ) constructor\n";
	}
	~AudioBook()
	{
		cout << "audiobook::~audiobook() destructor!\n";
	}
	virtual void print() const
	{
		cout << "AudioBook::print() -- I am an AudioBook object!\n"
			<< "My title is: " << _title << "\n"
			<< "My author is: " << _author << "\n"
			<< "My narrator is: " << _narrator << endl;
	}
	const string &narrator() const
	{
		return _narrator;
	}
protected:
	string _narrator;
};

void print(const LibMat &mat)
{
	cout << "in global print(): about to print mat.print()\n";

	mat.print();
}

int main(void)
{
	AudioBook ab("随遇而安","孟非", "good");
	print(ab);

	return 0;
}

程序输出:


2) 有点复杂的继承和多态

num_sequence.h:

#include <iostream>
using namespace std;

class num_sequence{
public:
	virtual ~num_sequence( void ){}
	virtual int	elem( int pos ) const = 0;
	virtual const char *who_am_i( void ) const = 0;
	static int max_elems( void ){
		return _max_elems;
	}
	virtual ostream &print( ostream &os = cout ) const = 0;
protected:
	virtual void gen_elems( int pos ) const = 0;
	bool		check_integrity( int pos, int size ) const;

	const static int		_max_elems = 1024;
};

bool num_sequence::check_integrity( int pos, int size ) const
{
	if ( pos < 0 || pos > _max_elems ){
		cerr << "!!invalid position: " << pos << " cannot honor request\n";
		return false;
	}

	if ( pos > size ){
		gen_elems( pos );
	}

	return true;
}

ostream &operator<<( ostream &os, const num_sequence &ns )
{
	return ns.print( os );
}

Fibonacci.h:

#include "num_sequence.h"
#include <iostream>
#include <vector>
using namespace std;

class Fibonacci : public num_sequence{
public:
	Fibonacci( int len = 1, int beg_pos = 1 ) : _length( len ), _beg_pos( beg_pos ){}
	virtual int		elem( int pos ) const;
	virtual const char *who_am_i( void ) const { return "Fibonacci"; }
	virtual ostream& print( ostream &os = cout ) const;
	int		length( void ) const { return _length; }
	int		beg_pos( void ) const { return _beg_pos; }
protected:
	virtual void gen_elems( int pos ) const;
	int			_length;
	int			_beg_pos;
	static vector< int >	_elems;
};
vector< int > Fibonacci::_elems;

int Fibonacci::elem( int pos ) const
{
	if ( !check_integrity( pos, _elems.size() ) ){
		return 0;
	}
	if ( pos > _elems.size() ){
		Fibonacci::gen_elems( pos );
	}

	return _elems[ pos - 1 ];
}

void Fibonacci::gen_elems( int pos ) const
{
	if ( _elems.empty() ){
		_elems.push_back( 1 );
		_elems.push_back( 1 );
	}
	if ( _elems.size() <= pos ){
		int ix = _elems.size();
		int n_2 = _elems[ ix - 2 ];
		int n_1 = _elems[ ix - 1 ];

		for ( ; ix <= pos; ix++ ){
			int elem = n_2 + n_1;
			_elems.push_back( elem );
			n_2 = n_1;
			n_1 = elem;
		}
	}
}

ostream &Fibonacci::print( ostream &os ) const
{
	int elem_pos = _beg_pos - 1;
	int end_pos = elem_pos + _length;

	if ( end_pos > _elems.size() ){
		Fibonacci::gen_elems( end_pos );
	}

	while ( elem_pos < end_pos ){
		os << _elems[ elem_pos++ ] << " ";
	}

	return os;
}

main.cpp:

#include <iostream>
#include "Fibonacci.h"
using namespace std;

int main( void )
{
	Fibonacci fib;

	cout << fib << endl;

	Fibonacci fib2( 4 );
	cout << fib2 << endl;

	Fibonacci fib3( 8, 12 );
	cout << fib3 << endl;

	return 0;
}

程序输出:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值