现在的位置: 首页 > 综合 > 正文

C++ 笔记

2012年08月07日 ⁄ 综合 ⁄ 共 2477字 ⁄ 字号 评论关闭
文章目录

1. 2011年5月26日

以前一般是因为MFC而不得不使用C++,但对C++的理解其实是很肤浅的。最近下了个决心,打算重头开始认真的学习C++。
为了最直接的接触C++的特色,我首先就重STL开始吧。因为其他的语法以前经常接触到,没有多少神秘感。

在网上找了本《C++标准库》,先囫囵吞枣的看了看,写了些测试的代码。对“STL组建”的理解,对于一直使用C的人来
说,这些东西概念真的很讨厌。

a. 容器(containers)
   我觉得是对象的集合叫做容器,所以就有vector,deque,list,set...等等。因为他们都是来存储数据的,
   仅仅是存储方式不同而已。

b. 迭代器(iterators)
   这个最讨厌,一开始见到这个名称“迭代器”,简直不知道啥意思。我暂时把他理解成在Containers里遍历元素
   的一个指针。

c. 算法(algorithms)
   就是算法,这个不用解释。因为stl的算法是和容器分开的,它不是面向对象的。

d. 仿函数(functors)
   很难理解,感觉跟C的回调函数很相似。

e. 配接器(adapters)
   还没接触过。
  
f. 我的测试代码。

/* test for template
** 这里写了个模板类,作为后面container的元素类型。
** operator <  : 用于为sort算法提供默认的比较函数。
** biger       :  用于比较两个元素的大小
** operator () :  仿函数,可以通过lpair对象来调用。
**/
template<class T1, class T2>
struct lpair{
	T1 first;
	T2 second;

	lpair(){}
	lpair( T1 v1, T2 v2 ) :	first(v1), second(v2){}
	
	lpair<T1,T2> add( const lpair a, const lpair b ){
		return lpair<T1,T2>(a.first+b.first, a.second+b.second);
	}
	/*just for sort */
	bool operator < ( const lpair b ){
		cout<<"operator <"<<endl;
		return first+second < b.first+b.second;
	}

	static bool biger ( const lpair a, const lpair b ){
		cout<<"lpair::biger"<<endl;
		return a.first+a.second > b.first+b.second;
	}

	bool operator ()( const lpair a, const lpair b ){
		cout<<"operator ()"<<endl;
		return a.first+a.second > b.first+b.second;
	}
};


/* test for vector
**/
std::vector< lpair<int,float> > vc;
void test_vector(){
	int i;
	for( i=0; i<10; i++ )	vc.push_back( lpair<int,float>(i,(float)i+2) );
	for( i=0; i<vc.size(); i++ )	std::cout<<vc.at(i).first<<"."<<vc.at(i).second<<std::endl;
}

/* test for deque
**/
std::deque< lpair<int,float> > dq;
void test_deque(){
	int i;
	for( i=0; i<10; i++ )	dq.push_back( lpair<int,float>(i,(float)i+2) );
	for( i=0; i<10; i++ )	dq.push_front( lpair<int,float>(i,(float)i+2) );
//	sort( dq.begin(), dq.end() );
//	sort( dq.begin(), dq.end(), lpair<int,float>::biger );
//	sort( dq.begin(), dq.end(), lpair<int,float>() );
	for( i=0; i<dq.size(); i++ )	std::cout<<dq.at(i).first<<"."<<dq.at(i).second<<std::endl;
}


/* test for list 
** list< lpair<int,float> >::iterator itor; 位迭代器。跟指针的用法很像。
**/
std::list< lpair<int,float> > lt;
void test_list(){
	int i;
	list< lpair<int,float> >::iterator itor;
	for( i=0; i<10; i++ )	lt.push_back( lpair<int,float>(i,(float)i+2) );

	itor = lt.begin();
	while( itor != lt.end() ){
		std::cout<<(*itor).first<<"--"<<(*itor).second<<std::endl;
		itor++;
	}

	while( !lt.empty() ){
		std::cout<<lt.front().first<<"--"<<lt.front().second<<std::endl;
		lt.pop_front();
	}
}

/* test for set
**/ 
std::set< lpair<int,float>, lpair<int,float> > st;
std::set< lpair<int,float>, lpair<int,float> >::iterator stor;
void test_set(){
	int i;
	for( i=0; i<10; i++ )	st.insert( lpair<int,float>(i, 5 ) );
	stor = st.begin();
	while( stor != st.end() ){
		std::cout<<(*stor).first<<"--"<<(*stor).second<<std::endl;
		stor++;
	}
}

抱歉!评论已关闭.