makefile
-------------------------------------
%.o : %.cpp g++ -g -c $< -o $@ all: t t2 rmXX % : %.o g++ $< -o $@ rmXX: echo "rmXX" rm *.o
--------------------------------
同目录头文件:
hTestSTL.h
---------------------------------
#include<iostream> using namespace std; class A { private: int a; int b; public: int aPlusB() { cout<<"a:"<<a<<endl; cout<<"b:"<<b<<endl; cout<<"b+b:"<<a+b<<endl; return a+b; }; void setA (int a) { this->a=a; }; void setB(int b) { this->b=b; }; }; class NodeInfo { private: int beanId; int value; public: NodeInfo() { cout<<"init bean"<<endl; }; void setBeanId(int id) { this->beanId=id; }; void setValue(int value) { this->value=value; }; int getValue() { return this->value; }; int getBeanId() { return this->beanId; }; };
----------------------------
练习1
t1.cpp 队列容器
-----------------------------
#include<iostream> #include "hTestSTL.h" #include<queue> using namespace std; queue<A> que; void showHowUsingQueue() { A a; A *p=&a; a.setA(100); a.setB(200); a.aPlusB(); que.push(*p); a.setA(1000); a.setB(2000); a.aPlusB(); que.push(*p); int tmp=0; A *tmp_p=0; while(!que.empty()) { que.pop(); tmp_p=&que.front(); tmp_p->aPlusB(); } cout<<tmp; }; int main(int c,char * argv[]) { showHowUsingQueue(); cout<< "hello"<<endl; A a; a.setA(100); a.setB(200); a.aPlusB(); int b ; cin >> b; return 0; };
---------------------
练习2 t2.cpp 访函数 迭代 遍历
------------------------
#include<iostream> #include "hTestSTL.h" #include<list> #include<iterator> #include<algorithm> using namespace std; void print( NodeInfo &elem) { cout<<elem.getValue()<<endl; }; struct Printer { template<typename T> void operator()( T& t ) { cout<<"printer:"<<t.getValue()<<endl; } }; struct Printer2 { void operator()( NodeInfo & t ) { cout<<"printer2:"<<t.getValue()<<endl; } }; void showHowUsingList() { list<NodeInfo> beanList; NodeInfo bean; for(int i=0;i<20;i++) { bean.setValue(i); beanList.push_back(bean); } for_each(beanList.begin(), beanList.end(), print) ; cout<<"test2"<<endl; for_each(beanList.begin(), beanList.end(), Printer()) ; cout<<"test3"<<endl; for_each(beanList.begin(), beanList.end(), Printer2()) ; }; int main(int c,char * argv[]) { showHowUsingList(); return 0; };