Lap Trinh Cpp Nang Cao

Embed Size (px)

DESCRIPTION

Easy to learn Cpp

Citation preview

  • LP TRNH C/C++ NNG CAOYu cu trc khi c: hc xong Lp trnh C/C++ cn bnBI 1: NHC LI V C/C++Nhp xut c bnCODE#definemax(a,b)(a>b)?a:b//khaibomacrotypedefunsignedintbyte;//nhnghakiud liuconstfloatPI=3.14;//khaibohngscharc;chars[20];

    Cch ca CCODE//khngdngscannumunnhpkhongtrnggets(s);//cth nhpkhongtrngputs(s);fflush(stdin);//xab mnhpc=getchar();putchar;

    Cch ca C++CODE//khngdngcin>>numunnhpkhongtrngcin.getline(a,21);//cth nhpkhongtrngcout

  • gi:add10(n);

    Khng hiu qu, a vn gi nguyn gi trCch 2:CODEvoidadd10(int*a){*a=*a+10;}gi:add10(&n);

    Hiu qu.Cch 3:CODEvoidadd10(int&a){a=a+10;}gi:add10(n);

    Hiu qu, tin hn cch 2.Nhp xut d liu vi kiu mng s nguynCODEinta[3];

    Truyn d liu trc tip theo kiu C, cch 1CODEfor(inti=0;i

  • CODEvoidinput(int[]);input(a);voidinput(int*a){for(inti=0;i
  • input(a);voidinput(inta[]){for(inti=0;i>a[i];}voidoutput(int[]);output(a);voidoutput(inta[]){for(inti=0;i
  • Xut mng s thc 2 chiu bng cch dng mallocCODEfloat**p;p=(float**)malloc(2);for(inti=0;i
  • BI 2: NHC LI V C/C++ (TIP THEO)Cu trc (struct)Con tr cu trc (struct pointer)CODEstructStudent{intid;};Student*s;Studentm;s=&m;s->id=3;//means(*s).idcouttemp;a.name=newchar[strlen(temp)+1];strcpy(a.name,temp);//phidngbintmStudentb=a;strcpy(b.name,a.name);//phidngstrcpy,nukhngs saochpach b nh

    Gi hm vi cu trcCODEstructStudent{charname[10];intid;};Studentm[3],a;m[0]=(Student){"Pete",1};add(m[0].name,&m[0].id);

    C 4 cch thm d liu vo cu trc.Cch 1CODEvoidadd(charname[],int*place){cin>>name;cin.get();cin>>*place;}add(a.name,&a.id);

    Cch 2CODE

  • voidadd(Student&s){cin>>s.name;cin.get();cin>>s.id;}add10(a);

    Cch 3CODEvoidadd(Student*s){cin>>(*s).name;cin.get();cin>>(*s).id;}add(&a);

    Cch 4CODEvoidadd(Student*s){cin>>s->name;cin.get();cin>>s->id;}add(&a);

    Ton t sizeof vi structCODEstructHello{charc;doubled;};

    sizeof(Mystruct)=12; v c ly mt 32-bit word (4 byte, khng phi 1 byte)Con tr (pointer)Con tr tr n mt con tr khcCODEchara='z';//a='z'vgi s ach caa=8277char*p=&a;//p=8277vgi s ach cap=6194char**p2=&p;//p2=6194vach cap2s lmtcig

    Con tr void (void pointer)Con tr void dng tr n bt c mt kiu d liu noCODEvoidincrease(void*data,intdataType){switch(dataType){casesizeof(char):

  • (*((char*)data))++;break;casesizeof(int):(*((int*)data))++;break;}}intmain(){charc=66;inta=-4;increase(&c,sizeof(char));increase(&a,sizeof(int));}

    Con tr hm (function pointer)Con tr hm dng tr n mt hmCODEintaddition(inta,intb){returna+b;}intsubtraction(inta,intb){returna-b;}int(*minuse)(int,int)=subtraction;intprimi(inta,intb,int(*functocall)(int,int)){return(*functocall)(a,b);}intmain(){intm=primi(7,5,&addition);intn=primi(20,m,minuse);cout

  • intnumber;ifstreaminf;ofstreamoutf;inf.open("input.txt");outf.open("output.txt");while(in>>number)outf
  • BI 3: NHC LI V LPC bn v lpCODEclassDate{intday;public:Date(int,inta=1);intmonth;voidsetDay(int);voidoutput();};intmain(){Dated(6);d.month=3;d.setDate(25);d.output();return0;}Date::Date(intday,intmonth){this->day=day;this->month=month;}voidDate::setDay(intday){this->day=day;}voidDate::output(){cout
  • Hm bn (friend function)CODEclassStudent{public:intid;friendboolequal(constStudent&,constStudent&);};intmain(){Students1;s1.id=2;Students2;s2.id=3;cout(a) hoc operator>>(cin,a) Overload 2 ton t nhp v xut ny ht sc quan trng v sau. Nhn tin mi khi cp pht b nh, dng xong phi lun hy i thu hi li b nh cp pht. V v sau game ci u tin hng u l b nh, ng li rc.CODEclassDate{public:intday;intmonth;friendistream&operator>>(istream&,Date&);friendostream&operator(istream&ins,Date&d){ins>>d.day;ins>>d.month;ins.get();//phixab mreturnins;}ostream&operator
  • returnouts;}intmain(){Dated;cin>>d;cout*dt;coutmonth=month;this->special=special;}Date::Date(constDate&d){this->day=d.day;this->month=d.month;this->special=newchar[strlen(d.special)+1];//cpphtb nh chonstrcpy(this->special,d.special);//phidngstrcpyvichararray}intmain(){Dated1(29,8,"birthday");Dated2(d1);cout
  • Ch v cp pht b nhiu g s xy ra khi chng ta khng th cp pht b nh ? V d chng ta vit 1 game RTS m mi phe tham chin c 10 t qun ?Gii quyt khi khng th cp pht b nh thnh cngChng ta vn thng cp pht b nh nh sauCODEchar*p;inti;couti;p=newchar[i+1];delete[]p;

    Nu chng ta khng th cp pht b nh ? CPP s nm (throw) ra mt ngoi l. C 2 cch x l chuyn nyCch mt l dng t kha nothrow. V th CPP vn to ra mt pointer nhng l 0CODEp=new(nothrow)char[i+1];if(p==0)cout

  • c=newchar[strlen(src.c)+1];strcpy(this->c,src.c);}return*this;}booloperator!=(constBase&b1,constBase&b2){return(strcmp(b1.c,b2.c));}Vchngtacth gitont nyBases2=s1;

    Tha k (inheritance)Trong C c th sinh ra bug, trong C++ chng s c tha k.CODEclassBase{protected:intid;Base(intid){this->id=id;}};classSub:publicBase{public:intcode;Sub(intcode,intid):Base(id){this->code=code;}};

    Hm o (virtual function)Hm Play trong lp MusicPlayer l mt hm o (virtual function)CODEclassMusicPlayer{public:virtualvoidPlay(){cout

  • public:virtualvoidPlay()=0;};classDVD:publicMusicPlayer{public:voidPlay(){cout
  • strings1,s2;s1+=s2;s1+='o';s1.append(s2);//ynhus1+=s2s1.append(s2,3,string::npos);//thmvos1t kt th 3nhts2s1.insert(7,s2);//thms2vosaukt th 7cas1*kchc (capacity)s.capacity()tr v kchc tiaifs.size()=15,s.capacity()=16(16-byte)ifs.size()=17,s.capacity()=32(two16-byte)*truyxutchui#includetry{cout
  • BI 4: TEMPLATEHm templateGi s chng ta cn vit mt hm tr v s nguyn ln nht gia 2 sCODEintmaximum(inta,intb){return(a>b)?a:b;}

    Ri n s thc chng ta cng lm nh vyCODEdoublemaximum(doublea,doubleb){return(a>b)?a:b;}

    Ri gi s nh vi lp Person chng ta cng phi lm nh vy (ton t > c overload)CODEPersonmaximum(Persona,Personb){return(a>b)?a:b;}

    C++ cung cp mt gii php cho vn ny, l templateCODEtemplateTmaximum(Ta,Tb){return(a>b)?a:b;}intmain(){inta=7;intb=5;cout

  • CODEinta[3],b[3];cout
  • BI 5: TEMPLATE (TIP)Li au uTa mun vit mt chng trnh tm kim phn t trong mt mng. Ta vit nh sauCODEtemplateintsearch(Ta[],intn,Tkey){intindex=0;while(index
  • }templatevoidArray::makeArray(T*&arr,intn){arr=newT[n];}templateT&Array::operator[](inti){return*(array+i);}templateintArray::seek(constT&key){intindex=0;while((index
  • template class nh trn th xem.Bn s khng vit c u nu khng s dng ci ny: prototype template function (khai bo nguyn mu cho hm template)(Hc my ci in u ny lm g nh ? Lm g ? Hy th cho hai cu th trong mt game banh i din nhau. H c bao nhiu hnh ng c th lm c lc ? Chuyn bng ? La bng ? n ? special Zidane-style skill ? Mike Tyson skill ? Hai mng cc hnh ng y phi em ra m chi ln nhau. Bi th mang ting l Advance C++ nhng thc ra trong lp trnh game vn ch l newbie)prototype template functionChun b mt tp tin tn l array.hCODE#ifndefARRAY_H#defineARRAY_H#includeusingnamespacestd;templateclassArray;templateboolequal(constArray&,constArray&);templateostream&operator
  • Cui cng l main.cppCODE#include"array.h"classPerson{intage;public:Person(){age=0;}Person(intage){this->age=age;}intgetAge()const{returnage;}friendbooloperator!=(constPerson&p1,constPerson&p2){returnp1.getAge()!=p2.getAge();}friendostream&operator
  • Trong phn trc ta xem cc v d dng cch tham chiu m tham chiu n con tr Trong phn ny chng ta s overloadton t = v vit copy constructor cng s dng li cch ny, m khng phi dng n prototype template functionCODE#include#includeusingnamespacestd;templateclassArray{public:intsize;T*elems;Array(int);Array(constArray*&);voidsetValue(constT&,inti);T&getValue(intn);Array&operator=(constArray*&);friendbooloperator!=(constArray&,constArray&);};templateArray::Array(intsize){elems=newT[size];}templatevoidArray::setValue(constT&value,inti){*(elems+i)=value;}templateT&Array::getValue(inti){return*(elems+i);}templateArray::Array(constArray*&src){size=src.size;elems=newT[size];for(inti=0;i
  • booloperator!=(constArray&a1,constArray&a2){if(a1.size!=a2.size)returntrue;elsefor(inti=0;i
  • BI 6: TEMPLATE (TIP THEO)

    Trnh bin dch v templateTrong bi trc chng ta thy mt iu hi l l, l file header array.h c ch th #include file source array.cpp. Ti sao nh vy ?Khi trnh bin dch gp template, n kim tra c php, nhng khng bin dch ngay.V d n gp template n khng th bin dch v n khng bit kiu d liu ca T.Khi n gp instance u tin ca template, v d template n bin dch v chng ta c phin bn vi kiu d liu int ca template.Khi n gp instance th hai ca template, v d template n cng li bin dch v chng ta c phin bn th hai ca template, phin bn vi kiu d liu double. Vn vn.

    Thng thng chng ta vit nh ngha lp v nguyn mu cc hm ca lp file header (ui .h) ri mi vit thn cho cc hm mt file source (ui .cpp), m file cpp ny include lun file header .Template phi lm ngc li. V l do ni trn, c nh ngha lp, nguyn mu cc hm ln thn ca cc hm ca mt lptemplate phi c bin dch cng nhau. Do khi tch ri nh ngha ca mt lp template ra cha trong mt file header ring, file header phi include file source cha thn cc hm ca lp template , ri mt file no khc mun dng template phi include ci file header .

    y cn mt phn na v export, ti ct i. C nhiu th sau ny ti cng s ct i, nhm gim ti cho chng trnh xung n mc ti thiu nht c th c. Nhng an tm l nhng th quan trng nht u c y .

    Dng t kha no, class hay typenameV c bn, s khc bit gia chng l khng r rng, c 2 u c cng ngha v cng cho kt qu nh nhau, bn mun dng t kha no cng c.Nhng c lc bn phi dng t kha typename, v dCODEtemplateclassThing{T::SubType*ptr;};

    Chng ta mun khai bo 1 con tr thuc kiu SubType ca T, nhng C++ s hiu l chng ta mun nhn gi tr SubType ca kiu T vi ptr Lc ny chng ta bt buc phi dng t kha typenameCODEtemplateclassThing{typenameT::SubType*ptr;};

    Chuyn mn ha template (template specialization)Gi s ta c mt lp templatetemplateclass pair{}Khi ta to mt instance bng cch khai bo c th kiu ca T, v d l int, tc l ta chuyn mn ha (specialization) lp template pair myobject(155,36);i khi ta mun lp template to ra nhng instance c th thc hin nhng cng vic c th ring i vi mt loi d liu c th no , ta dng chuyn mn ha c th (explicit specialization)Trong v d di y ta mun ring i vi kiu d liu c th l int th lp template c mt hm tr v phn d gia hai s nguyn, cn vi cc kiu d liu khc th n tr v 0CODEtemplateclasspair{Tvalue1,value2;

  • public:pair(Tfirst,Tsecond){value1=first;value2=second;}Tmodule(){return0;}};//vitlinhnghalpchuynmnhachokiud liuinttemplateclasspair{intvalue1,value2;public:pair(intfirst,intsecond){value1=first;value2=second;}intmodule();};//hmmodulednhringcholpchuynmnhatemplateintpair::module(){returnvalue1%value2;}intmain(){pairmyints(100,75);cout
  • i s kiu primitive, v d kiu intCODEtemplateclassArray{T*array;public:Array();};templateArray::Array(){array=newT[size];}intmain(){Arraya;return0;}

    i s l mt lp template khcCODE#include#includeusingnamespacestd;templateclassArray{T*array;public:Array();};templateArray::Array(){array=newT;}templateclassStack{U*elems;public:Stack();};templateStack::Stack(){elems=newU[size];}intmain(){Stacka;return0;}

    Cn my phn na, nhng rt cao v t dng v sau trong lp trnh game, m ch yu cho lp trnh bc thp, phn cng, h iu hnh, nn ti b, nh th ny nhc u v kh nh ri. Cc bc hc xong template ri , nm r tt c cc k thut vtemplate chun b cho hc STL v sau.

  • Lm ci bi tp ch nh. n gin thi: lp trnh mt danh sch lin kt n dng template, cc php thm, xa, sa, truy xut. C sn ci chng trnh mu di ny. Chng trnh ny cc yu, khng c xa, hy Chng trnh cn cc bc b sung .CODEtemplateclassNode{Tdata;Node*next;public:Node(Tdata){(*this).data=data;(*this).next=0;}TgetData(){returndata;}voidsetData(Tdata){(*this).data=data;}Node*getNext(){returnnext;}voidsetNext(Node*next){(*this).next=next;}};templateclassList{Node*front;Node*rear;Node*current;public:List(){(*this).front=(*this).rear=(*this).current=0;}List(constList&l()){(*this).front=(*this).rear=(*this).current=0;Node*temp=new(nothrow)Node;if(temp==0)exit(1);temp=l.front;while(temp!=0){insertRear(temp->getData());temp=temp->getNext();}}~List(){Node*temp=new(nothrow)Node;if(temp==0)exit(1);while(front!=0){temp=front;front=(*front).next;deletetemp;}}voidinsertFront(Tdata){Node*temp=new(nothrow)Node;if(temp==0)exit(1);(*temp)->setData(data);if(front==0)rear=temp;elsetemp->setNext(front);front=temp;}voidinsertRear(Tdata){Node*temp=new(nothrow)Node;if(temp==0)exit(1);(*temp)->setData(data);if(rear==0)front=temp;elserear->setNext(temp);rear=temp;}voidreset(){if(front!=0)current=front;}voidnext(){if(current!=0)current=current->getNext();}TgetCurrentData(){if(current!=0)returncurrent->getData();}boolendOfList(){return(current==0);}

  • };

  • BI 7: CONST, STATIC, EXCEPTION, CASTING (BIN HNG, BIN TNH, NGOI L, P KIU)CONSTconst int p v int const p l nh nhau

    int* const p ngha l mt hng s loi con tr m tr n mt bin s kiu nguyn, ngha l bn khng th thay i con tr ny tr n mt ni khc c naCODEinta=3;intb=5;int*constp=&a;p=&b;//khnghpl

    const int* p ngha l mt bin s loi con tr m tr n mt hng s kiu nguyn, ngha l bn c th thay i con tr ny tr n mt ni khc, nhng khng th thay i d liu ni n tr nCODEinta=3;intb=5;constint*p=&a;p=&b;//hpl*p=6;//khnghpl

    const int *& p ngha l mt tham chiu m tham chiu ti mt bin s loi con tr m tr n mt hng s kiu nguyn

    int const *& p ngha l mt tham chiu m tham chiu ti mt hng s loi con tr m tr n mt bin s kiu nguyn

    Mt bin s const ngha l bin phi c gn gi tr ngay lc khai bo v gi tr y vnh vin khng thay i (ci ny qu ph bin ri)

    Mt hm s const ngha l hm s s khng thay i gi tr ca bt c tham s no ca n. Mt hm s phi c khai bo const nu n c t nht mt tham s constCODEclassTree{intage;public:intgetAge()const{returnage;}friendostream&operator

  • hello()=3;

    Nn chng ta phi thay i n tr v constCODEconstint&hello(){inttemp=5;returntemp;}

    Bo v tham sHn bn cn nh v d ny chCODEvoidadd10(int*a){*a=*a+10;}add10(&n);

    ngha y l, mt hm hon ton c th thay i gi tr ca tham s nu ta truyn vo n a ch ca bin . M vic truyn a ch l vic phi lm. V i khi khng th khng truyn a ch, v d kiu mngCODEvoiddosomething(char*a){...}char*m="hello";dosomething(m);

    Khi ta dng t kha const ngn vic hm thay i gi tr ca i sCODEvoiddosomething(constchar*a){...}char*m="hello";dosomething(m);

    STATICMt bin s const ngha l bin phi c gn gi tr ngay lc khai bo v gi tr y vnh vin khng thay iMt bin s static ngha l bin phi c gn gi tr ngay trc khi to mt instance ca mt lp v gi tr y c thay i, nhng ch c duy nht mt bin static y tn ti i vi tt c instance ca lp CODEclassMyClass{public:staticinti;};intMyClass::i;//tnticlp,khngph thucinstanceintmain(){MyClass::i=30;MyClassx,y;x.i=26;cout

  • CODEclassMyClass{public:staticvoidprint(char*s){cout
  • Khi chng ta bt c mt ngoi l, chng ta c th nm n ra bt li mt ln na bng throw;CODEclassDivideByZero{public:voidmsg(){cout
  • }Chng ta c th nm ra nhiu th bng mt ch th try v bt li tt c mi th, mi th mt ch th catch khc nhauCODEintmain(){try{intsize;cin>>size;if(size>10)throw"Sobig";elsethrowsize;}catch(intn){cout
  • CODEclassBase{};classDerived:publicBase{};Base*b=newDerived;Derived*d=static_cast(b);

    bng dynamic_castCODEclassBase{virtualvoidfunc(){}};classDerived:publicBase{};Base*b=newDerived;Derived*d=dynamic_cast(b);

    upcastp kiu cc con tr v cc i tng t kiu lp con thnh kiu lp cha, c gi l upcast. upcast him dng hn downcast. C 2 cch thc hin upcastbng static_castCODEclassBase{};classDerived:publicBase{};Derived*d=newDerived;Base*b=static_cast(d);

    bng dynamic_castCODEclassBase{virtualvoidfunc(){}};classDerived:publicBase{};Derived*d=newDerived;Base*b=dynamic_cast(d);

    const_cast (p kiu hng)const_cast dng ch yu vi cc con trconst_cast dng thay i mt bin s thnh mt hng s (thm t kha const vo)CODEinta=3;int*b=&a;*b=8;//hplconstint*c=const_cast(b);*c=5;//khnghplcout

  • reinterpret_cast (p kiu thng dch li)reinterpret_cast s p kiu bt c con tr hay i tng no m khng h c s kim tra no c. Khng khuyn khch dng v bygi ta cng cha phi dng, s hc sau.

  • BI 8: STL - SEQUENTIAL CONTAINERYu cu: hc xong mn cp trc d liu v gii thut c bn hoc tng ng c kin thc c bn v cc cu trc d liu ng nh danh sch lin kt (linked list), hng i (queue), ngn xp (stack), tp hp (set), nh x (map) v cc gii thut tm kim, sp xp c bn.

    STL (Standard Template Library) l mt b th vin v cng hu dng ca C++ dng lm vic vi cc cu trc d liu ph bin nh danh sch, hng i, ngn xp v cc php ton ch yu vi cc cu trc d liu ny nh tm kim, sp xp, truy xut, thm, xa, sa.

    STL bao gm

    *Cc container (cc b lu tr d liu) l cc cu trc d liu ph bin template ha dng lu tr cc kiu d liu khc nhau. Cc container chia lm 2 loi:-sequential container (cc b lu tr d liu tun t) bao gm list, vector v deque-associative container (cc b lu tr d liu lin kt) bao gm map, multimap, set v multiset*Cc iterator (cc con tr d liu) l cc con tr tr n cc phn t trong cc b lu tr*Cc algorithm (cc thut ton lu tr d liu) l cc hm ph bin lm vic vi cc b lu tr nh thm, xa, sa, truy xut, tm kim, sp xp*Cc function object (cc i tng hm) l cc hm v php ton ph bin lm vic vi cc phn t c lu tr cng nh cc b lu tr v cc thut ton lu tr nh cng, tr, nhn, chia, so snh*Cc adapter (cc b tng thch) Cc adapter chia lm 3 loi-container adapter (cc b tng thch lu tr) bao gm stack, queue v priority_queue-iterator adapter (cc b tng thch con tr)-function adapter (cc b tng thch hm)

    Trc tin ta hc v cc container.LISTCODE#include

    list rong STL l danh sch lin kt i, khng h tr random access (truy xut d liu bt k) Ngha l nu bn mun truy xut mt phn t bt k trong list th bn phi truy xut t phn t u tin hoc phn t cui cng ca list ri truy xut dn n phn t

    Khi to sao chplist c th khi to sao chp t mng, t list khc hoc t cc container khcCODEint a[10];list list1(a+2,a+7);list list2(list1.begin()++,--list1.end());

    Cc hm thng dng ca listCODEvoid push_front(T element): a mt phn t vo u listvoid push_end(T element): a mt phn t vo cui listvoid pop_front(): g phn t u list ravoid pop_end(): g phn t cui list raiterator begin(): tr v iterator tr n phn t u listiterator end(): tr v iterator tr n phn t cui list

    Vi d di chng ta to mt list, a phn t vo v truy xut phn t

  • CODElist list1;list1.push_back("Zebra");list1.push_back("Penguin");list1.push_front("Lion");list::iterator i;for(i=list1.begin();i!=list1.end();++i) cout
  • #include

    vector ging list ngoi tr-cho php random access, vi operator[], ngha l v[5], v[6], etc nh mng-c ti u ha vi cc php ton pha ui (rear operations)-khng c sn cc hm push_front,pop_front,splice,sort,merge,reserveCODEvector v;v.push_back(5);cout

  • vector v, v2;merge(v1.begin(),v1.begin()+5,++v2.begin(),v2.end(),v1.begin());//hp 2 phn d liu, phn mt t v1.begin() n v1.begin()+5, phn hai t ++v2.begin() n v2.end(), sau chp tt c vo v1 bt u t v1.begin()swap(v1, v2);

    CC PHN T L CON TRGi s ta c lp Person vi hm khi to Person(char* name)CODE a mt phn t Person vo vector:vector v;v.push_back(Person("C")); a mt phn t con tr Person vo vector, ta phi dng new cp pht b nh:vector vp;vp.push_back(new Person("M")); truy xut phn tvector::iterator i;for(i=v.begin();i!=v.end();++i) cout

  • BI 9:FUNCTION OBJECT (I TNG HM)Function objectMt function object (i tng hm) l mt object (i tng) c s dng nh mt function (hm). Mt Mt function object l mt instance ca mt lp m lp phi c t nht mt hm tha-quyn truy xut phi l public-phi l mt hm thnh vin, khng phi l mt hm friend-khng phi l mt hm static-c khai bo operator()V d ta vit mt hm bnh thng nh sauCODEvoidiprintf(inti)const{cout
  • {cout
  • list::iteratori=find_if(l.begin(),l.end(),IsOdd);if(i!=l.end())cout
  • Hm searchHm search tm v tr ca mt chui con trong mt chui ln hn, nu tm thy th tr v iterator tr n v tr ca chui con trong chui ln. Hm ny c hai phin bnCODEinta[]={3,4,5};vectorv;for(inti=0;i
  • {public:voidoperator()(constT&t){cout
  • BI 10:TH VIN FUNCTIONALCODE#include

    Hng ca mt predicateC nhiu s mp m do t ng ngha gia cc khi nim ton hc trong c hai ngn ng ting Vit v ting Anh, do nh ngha sau ch mc c gng chnh xc nht c th c:S ton t (operand) ca mt php ton (operator), tng ng l s i s (argument) ca mt hm (function), c gi l hng (arity) ca php ton hay hm Tng t, s ton t (operand) ca mt biu thc (expression), tng ng l s i s (argument) ca mt i tng hm (functor), c gi l hng (arity) ca biu thc hay i tng hm V dUnary (n nguyn, n phn, mt ton hng, mt ngi)n! (giai tha ca n) l mt unary operatorn! l mt unary expression, ch bao gm mt unary operatorint giaithua(int n) l mt unary functionmt object ca class giaithua{int operator()(int n)} l mt unary functorBinary (nh nguyn, nh phn, hai ton hng, hai ngi) a + b l mt binary expression, ch bao gm mt binary operatorint addition(int a,int b) l mt binary functionmt object ca class addition{int operator()(int a,int b)} l mt binary functorTernary (tam nguyn, tam phn, ba ton hng, ba ngi) b * b 4 * a * c l mt ternary expression, bao gm mt unary operator v ba binary operatordouble delta(double a, double b,double c) l mt ternary functionmt object ca class delta{ double operator()(double a, double b,double c)} l mt ternary functorn-ary (a nguyn, a phn, nhiu ton hng, nhiu ngi) Tng t nh trn, ngoi ra cn c nhiu t gc Latin khc nh quaternary (bn ton hng) quinary (nm ton hng) gi chung l nhiu ton hng.Hng ca predicate tc l hng ca function hay functor m ng vai tr predicate. Nh v d trn, addition l mt binary predicate, delta l mt ternary predicateCu trc unary_function trong th vin functionalTrong th vin functional nh ngha sn cu trc unary_functionCODEtemplatestructunary_function{typedefArgargument_type;typedefResultresult_type;};

    unary_function l cu trc nh ngha sn cho tt c unary function v unary functor vi Arg l kiu d liu ca i s v Result l kiu tr v ca hm c operator()Chng ta vit li lp IsOdd, nh ngha n l mt unary_functionCODEclassIsOdd:publicunary_function{public:booloperator()(intn)const{returnn%2;}};

  • Cu trc binary_function trong th vin functionalTng t, trong th vin functional nh ngha sn cu trc binary_functionCODEtemplatestructbinary_function{typedefArg1first_argument_type;typedefArg2second_argument_type;typedefResultresult_type;};

    binary_function l cu trc nh ngha sn cho tt c binary function v binary functor vi Arg1 l kiu d liu ca i s th nht v Arg2 l kiu d liu ca i s th hai v Result l kiu tr v ca hm c operator()Chng ta vit li lp compare, nh ngha n l mt binary_functionCODEclasscompare:publicbinary_function{public:booloperator()(inti,intj)const{returni==j;}};

    Tng t chng ta c th t vit cc cu trc ternary_function, quaternary_function, vn vn nu mun. V d di y l mt cu trc ternary_function t vit v mt lp c nh ngha l mt ternary_functionCODEtemplatestructternary_function{typedefArg1first_argument_type;typedefArg2second_argument_type;typedefArg3third_argument_type;typedefResultresult_type;};classmultiply:publicternary_function{public:doubleoperator()(inti,floatf,longl)const{returni*f*l;}};

    Rng buc (bind) ton hng cho predicateC nhiu hm ch chp nhn mt i s, nhng chng ta li cn chuyn vo cho n cc predicate l binary predicate nh binary function hay binary functor. Trong trng hp chng ta cn rng buc ton hng cho binary predicate n tr thnh mt unary predicateV d chng ta cn dng hm find_if tm cc phn t trong mt vector tha mt binary predicate, nhng find_if li ch chp nhn unary predicate, khi chng ta cn rng buc ton hng cho binary predicate n tr thnh mt unary predicatebinary predicate mun c rng buc ton hng phi c nh ngha l mt binary_functionHm bind1stHm bind1st rng buc ton hng th nht ca mt binary predicate vi mt gi tr cho trc n tr thnh mt unary predicate

  • vi i s cn li ca binary predicate ban u tr thnh i s ca unary predicate kt quCODEclasscompare:publicbinary_function{public:booloperator()(inti,intj)const{returni+1==j;}};intmain(){vectorv;v.push_back(4);v.push_back(0);v.push_back(1);vector::iteratori=find_if(v.begin(),v.end(),bind1st(compare(),0));if(i!=v.end())cout
  • CODEvectorv;

    Hm ny c 2 phin bnSp xp li mt chui phn t theo th t tng dn (ascending)CODEsort(v.begin(),v.end());

    Sp xp li mt chui phn t tha mt binary predicateCODEtemplateclassBigger{public:booloperator()(constT&t1,constT&t2){returnt1>t2;}};templateclassOutput{public:voidoperator()(constT&t){cout

  • CODEinta[]={1,-2,3};transform(a,a+3,a,negate());for_each(a,a+3,Output());

    V d plusCODEinta[]={1,2,3,4,5};intb[]={6,7};intc[5];transform(a,a+5,b,c,plus());

    bi trn c mt iu ng ch , bn t tm xemV d modulusCODEinta[]={1,2,3,4,5};intb[]={2,2,2,2,2};intc[5];transform(a,a+5,b,c,modulus());

    Ci v d hm modulus ny hi k k. Modulus l mt binary function, gi s by gi chng ta mun cc phn t ca a lun modulus cho 2 th lm th no ? Phi rng buc ton hng cho modulus n tr thnh mt unary function thi.CODEinta[]={1,2,3,4,5};intb[5];transform(a,a+5,b,bind2nd(modulus(),2));

    Cc hm so snhBao gm equal_to (==) not_equal_to (!=) greater (>) less (=) less_equal(

  • BI 11 ASSOCIATIVE CONTAINER (CC B LU TR LIN KT)Bao gm map (nh x) multimap (a nh x) set (tp hp) multiset (a tp hp)S khc nhau gia cc associative container v sequential container mt im:-cc sequential container lu tr cc phn t (gi l cc value) v cc value ny c truy xut tun t theo v tr ca chng trong b lu tr-cc associative container lu tr cc phn t (gi l cc value) v cc kha (gi l cc key) lin kt vi cc value v cc value ny c truy xut theo cc key m chng c lin ktMapCODE#includemapnhx t mtchar*nmtintmapmapInt;mapInt["one"]=1;cout
  • mapPerson.insert(pr);

    value_type thc cht cng l mt pairComparatorMt functor dng so snh, sp xp, etc cc phn t trong mt map gi l mt comparator. Khi map thay v c 2 argument nh map th c 3 argument l mapDng comparator so snhCODEclasscomparePerson{public:booloperator()(Personp1,Personp2){returnp1.name.compare(p2.name);}};typedefmapMAP;MAPpMap;Personp=newPerson(...);MAP::iteratori=pMap.find(d);if(i==pMap.end())pMap.insert(MAP::value_type(d,1));

    Dng comparator sp xpCODEclasscomparePerson{public:booloperator()(constPerson&p1,constPerson&p2){returnp1.name.compare(p2.name);}};typedefmapMP;MPmapPerson;Personp("Viet");mapPerson.insert(pair("one",Person("Nam")));mapPerson.insert(pair("two",Person("Viet")));mapPerson.insert(pair("three",Person("An")));display(mapPerson);

    Bn lu l tt c cc asociative container u c xy dng sn comparator mc nh l less (trong th vin functional) Ngha l khi bn khai boCODEmapmapInt;

    thc ra lCODEmapmapInt;

    V dCODEtypedefmapMI;typedefmap::iteratorMII;MIm;m["c"]=1;m["b"]=2;m["a"]=3;

  • for(MIIi=m.begin();i!=m.end();++i)cout
  • cout
  • BI 12: CC B TNG THCH V CC TH VIN KHCcontainer adapter (cc b tng thch lu tr)Bao gm stack, queue v priority_queueCc b tng thch lu tr, di y gi l cc b tng thch, lm cc b lu tr khc tr nn tng thch vi n bng cch ng gi (encapsulate) cc b lu tr khc tr thnh b lu tr c s ca n. V dCODEstacks;

    Khi vector tr thnh b lu tr c s ca b tng thch stackNu khng khai bo b lu tr c s, stack v queue mc nh s dng deque lm b lu tr c s, trong khi priority_queue mc nh s dng vector lm b lu tr c s, c ngha l khi khai boCODEstacks;

    thc ra lCODEstacks;

    stack v queuestack l LIFO, queue l FIFO, xem th s khc bit qua v d palindrome sau(lu , palindrome tc l mt t c xui hay ngc u nh nhau, v d 12321, level, aka)CODE#include#includeusingnamespacestd;intmain(){stackstackInt;queuequeueInt;chara;//storetempuserinputintn;//noofnumbersuserintendtoinputcoutn;for(inti=0;i>a;stackInt.push(a);queueInt.push(a);}for(inti=0;i

  • priority_queuepriority_queue l queue trong phn t u tin lun lun l phn t ln nht theo mt tiu chun sp xp no priority_queue ging nh khi nim heap (ng) m ta bit (heap v gii thut heapsort trong mn CTDL)Thc ra priority_queue ch l queue mc nh c ci sn thm comparator less ging nh cc associative container thi. Ta c th ci li comparator do ta nh ngha cho n (v d bi di y ci greater)CODE#includeclassPlane{intfuel;public:Plane(intfuel){(*this).fuel=fuel;}friendostream&operator
  • cout
  • listl;l.push_back(newPerson(4));l.push_back(newPerson(5));for_each(l.begin(),l.end(),mem_fun(&Person::display));return0;}

    mem_fun_refChuyn mt hm thnh vin (member function) ca mt lp thnh mt functor v truyn vo functor ny cc i s l cc tham chiu m tham chiu n cc i tng ca lp CODEclassPerson{intage;public:Person(intage):age(age){}intdisplay(){cout

  • Hm accumulate truyn vo functor acc (do ptr_fun chuyn t function thnh functor) tham s l total = 0.0 v ln lt l cc phn t ca set, sau acc tnh tng total v cc element ri tr v accumulate tch ly v cui cng tr gi tr ra bin sumTh vin bitsetbitset c cu trc ging nh mt mng, nhng mi phn t ch chim mt bit (nn nh kiu d liu char mi phn t chim 8 bit)V d sau ta khi to mt bitset 7 phn t vi 5 phn t u l 1,1,0,1,0CODE#includebitsetb(string("01011"));for(inti=0;i
  • BI 13: RTTI, I/O, EXTERN V PREPROCESSOR DIRECTIVERTTI (Runtime type identification)Trong Java, bit mt object c phi l mt instance ca mt class hay khng, ta dng instanceofif(os instanceof ostream)Trong C++ ta dng hm typeidif(typeid(os)==typeid(ostream))Trong C++, nu ta mun overload ton t xut > (input) 2 ln cng vi istream v ifstream, v ifstream l lp con ca istream.

    Khi pht trin nhng game thng mi ln nu "lt s" nhng li ngm kh pht hin nh vy th khi c "chuyn g" xy ra, vi s lng kinh hong cc lp v cc ton t c pht trin th thi gian i tm v sa li s cng rt ... kinh hong. Do , m bo an ton, khi phi overload cng mt ton t cho 2 lp cha v con, phi s dng RTTI

    Ta s dng RTTI bng cch dng typeid v downcast bng dynamic_cast. RTTI (Runtime type identification) (xc nh kiu d liu lc thc thi) Lc thc thi, chng trnh s xc nh kiu d liu ca object chnh xc l instance ca cha hay con. Trc ht, ta vit ring hm cho con trc. Nu xc nh l instance ca con, ta p kiu ca object xung thnh kiu ca con ri cho thc hin hm ta vit ring cho con. Nu khng phi l vn thc hin hm ca cha nh bnh thng. Lp cha phi c hm o (istream v ostream u tha iu ny)

    V d di y ta vit 2 hm printToFile v readFromFile dnh cho con (ofstream v ifstream) trc ri dng typeid v downcastCODE#include#includeusingnamespacestd;classPerson{char*name;public:Person(){}Person(char*name):name(name){}voidsetName(char*name){(*this).name=newchar[strlen(name)+1];strcpy((*this).name,name);}char*getName()const{returnname;}voidprintToFile(ofstream&os)const{os*this;}friendostream&operator

  • (*buf).sgetn(temp,size);//chuynt buffervomngktcout.write(temp,size);//vitmngkt volungxutramnhnhstrings(temp);//chuynmngkt rachui

    Th vin C 2 lp phi ch l ostringstream v istringstreamNhng i tng c a vo ostringstream vn gi nguyn kiu d liu ca n ch khng h chuyn kiu thnh string, v dCODEstrings="Hithere";doubled=45.67;intn=2;ostringstreamoutput;outputd>>n;

    By gi ta c th xut ton b d liu trong mt file ra dng filebufCODEfilebuf*buf=fin.rdbuf();...strings(temp);istringstreamvalues(s);values>>s1>>s2>>s3>>...;

    T kha externT kha extern thng bo vi trnh bin dch l mt phn ca chng trnh c lin kt vi mt ngn ng khc hoc c khai bo theo mt qui c khc hoc trong mt phn chng trnh khc.Trng hp th nht: ta c mt tp tin c.obj cha m nh phn ca hm dosomething vit bng C. By gi ta mun vit mt chng trnh C++ s dng th vin y. Ta khai bo trong main.cppCODEextern"C"{voiddosomething(inti);}intmain(intargc,char**argv){dosomething(5);}

    Trng hp th hai: ta c mt th vin ha vit bng C l graphics.lib v tp tin header ca n l graphics.h. By gi ta mun vit mt chng trnh C++ s dng th vin y. Ta khai bo trong main.cppCODEextern"C"{#include"graphics.h"}

    Trng hp th ba: ta c mt d n c 2 tp tin 1.cpp v 2.cpp trong d bin a v hm in khai bo tp tin 1.cpp nh sauCODEinta=7;voidin(inta){cout

  • add(2*((-5>0)?-5:-(-5)));return0;}

    Cc ch th tin x l (preprocessor directive)#define: nh ngha mt macro (qu d ri)#include: bao gm mt tp tin hay macro vo chng trnh (qu d ri)#undef: hy b nh ngha mt macro, macro c th nh ngha li bng #define, v dCODE#definemax(a,b)((a>b)?a:b)#undefmax#definemax(a,b)((a>b)?2*a:3*b)

    #error: nh ngha cu thng bo khi gp li, v dCODE#errorbiloiroiintmain(){inta=10/0;}

    Cu thng bo li s l cu ta nh ngha#pragma: cc ty chn ch th bin dch (ty thuc vo trnh bin dch) Cc ch th iu kinBao gm #if (ngha l if) #elif (ngha l else if) #else (ngha l else) #endif (ngha l end if) v d on m sauCODE#ifMAX_WIDTH>10#undefMAX_WIDTH#defineMAX_WIDTH10#elsifMAX_WIDTH10){#undefmax_width;max_width=10;}else{if(max_width

  • {cout
  • BI 14: DESTRUCTOR, CONSTRUCTOR, CONVERSION V DEBUGHm hy o (virtual destructor)Trong v d sau, hm hy ca Derived s khng c giCODEclassBase{public:Base(){};~Base(){};};classDerived:publicBase{public:Derived(){};~Derived(){};};intmain(){Base*b=newDerived();deleteb;}

    Trong trng hp ny, ta cn khai bo hm hy ca Base l hm hy o (tuyt i khng c l pure virtual destructor)CODEclassBase{public:Base(){};virtual~Base(){};};

    Hm khi to chuyn kiu (conversion constructor)Bt k mt constructor mt i s no u c th tr thnh mt conversion constructorCODEclassThing{intnum;public:Thing(intnum){(*this).num=num;}friendostream&operator

  • -c khai bo operatorCODEclassViDu{char*s;intx,y;public:ViDu(char*s,intx,inty):s(s),x(x),y(y){}operatorchar*(){returns;}operatorint(){returnx*y;}operatorViDu(){}intoperator()(inti){returni;}};intmain(){ViDuv("hello",5,3);cout
  • null pointer l mt nguy him cht ngi ta hay gp phiCon tr m tr ti mt null pointerCODEint*p=NULL;int**pp=&p;cout
  • CODEtry{int*a=newint[5];cout
  • {int*a=(int*)xmalloc(2,__FILE__,__LINE__);char*b=(char*)xmalloc(4,__FILE__,__LINE__);double*c=(double*)xmalloc(8,__FILE__,__LINE__);xfree(a);xfree(c);for(lmii=lmi.begin();lmii!=lmi.end();++lmii){MEM_INFOmemInfo=*lmii;cout
  • cout
  • for(lmii=lmi.begin();lmii!=lmi.end();++lmii){if((*lmii).address==p){lmi.erase(lmii);break;}}}void*operatornew[](unsignedintsize,char*file,intline){void*ptr=malloc(size);if(ptr!=NULL){MEM_INFOmemInfo;memset(&memInfo,0,sizeof(MEM_INFO));memInfo.address=ptr;memInfo.size=size;strcpy(memInfo.file,file);memInfo.line=line;lmi.push_back(memInfo);}returnptr;}voidoperatordelete[](void*p){delete[]p;for(lmii=lmi.begin();lmii!=lmi.end();++lmii){if((*lmii).address==p){lmi.erase(lmii);break;}}}};intmain(){MyClass*a=new(__FILE__,__LINE__)MyClass;MyClass*b=new(__FILE__,__LINE__)MyClass[5];for(lmii=lmi.begin();lmii!=lmi.end();++lmii){MEM_INFOmemInfo=*lmii;cout
  • BI 15: AUTO_PTR, MUTABLE, VOLATILE V NH GI TC CHNG TRNHauto_ptrTrong th vin c nh ngha lp auto_ptr (ngha l con tr cp pht v hy b vng nh t ng) gii quyt vn r r b nh (tuy vy vn c phin toi, do lp trnh vin t cp pht v gii phng b nh vn l la chn c khuyn khch hn)Trong v d di y, p tr n a (gi l p s hu a) Bn khng cn gi delete a Khi chng trnh kt thc, destructor ca p c gi, p s b hy, n s t ng hu lun a cho bn. l mc ch ca auto_ptr, bn khng phi lo v leak memoryCODE#includeclassMyClass{intdata;public:MyClass(intdata):data(data){}friendostream&operator
  • return0;}

    const auto_ptr khng th chuyn quyn s hu c na, v d sau l khng hp lCODEMyClass*a=newMyClass(5);constauto_ptrp(a);auto_ptrp2=p;

    Rc ri th hai l auto_ptr khng c dng vi cu trc b nh ng, nh mng hay cc b lu tr ca STL nh vector, listCODEint*a=newint[5];auto_ptrp(a);

    l do l v khi destructor ca p c gi, n s gi delete a, ch khng phi delete [] aVi cc b lu tr ca STL nh vector, list, cn l do l khi a phn t vo, cc b lu tr ny ch sao chp gi tr ca phn t gc v sau lm vic vi cc bn sao chp. Trong khi vi auto_ptr, cc bn sao chp ny l KHNG ging nhau.Do tut i khng bao gi dng (d chng thy bo li g c)CODEvectorv;

    auto_ptr c mt vi hm tin chhm resetp tr n a ri, by gi ta tr p n b, th vng nh do a tr n s b ph hyCODEMyClass*a=newMyClass(5);cout

  • auto_ptrp(a);auto_ptrp2(p.get());

    v p vn cn quyn s hu a v p2 khng th chim ly a chm releaseHm release y nh hm get thm na l auto_ptr t b s quyn s hu vng nhKhi vn trn vi hm get c gii quytCODEauto_ptrp(a);auto_ptrp2(p.release());

    v p t b quyn s hu a nn p2 c th chim ly amutableTrong mt s trng hp, chng ta cn mt bin s const c th thay i gi tr.V d chng ta cn thay i gi tr ca a bng hm affectCODEclassMyClass{public:inta;MyClass(inta):a(a){}intaffect()const{returna++;//xuatraroimoithuchienphepcong}};

    Trong trng hp ny const_cast l mt gii php ht sc trnh, const_cast khng m bo n b i const vi nhng object c khai bo const, do c th gy ra li khng lng c, v dCODEclassMyClass{public:inta;MyClass(inta):a(a){}intaffect()const{MyClass*mc=const_cast(this);return(*mc).a++;}};intmain(){constMyClassm(6);cout

  • }};intmain(){MyClassm(6);cout
  • //dosomethingtime(&time2);cout
  • This post has been edited by vietgameprogramming

    BI 1: NHC LI V C/C++BI 2: NHC LI V C/C++ (TIP THEO)BI 3: NHC LI V LPBI 4: TEMPLATEBI 5: TEMPLATE (TIP)BI 6: TEMPLATE (TIP THEO)BI 7: CONST, STATIC, EXCEPTION, CASTING (HNG, BIN TNH, NGOI L, P KIU)BI 8: STL -SEQUENTIAL CONTAINERBI 9:FUNCTION OBJECT (I TNG HM)BI 10:TH VIN FUNCTIONALBI 11 ASSOCIATIVE CONTAINER (CC B LU TR LIN KT)BI 12: CC B TNG THCH V CC TH VIN KHCBI 13: RTTI, I/O, EXTERN V PREPROCESSOR DIRECTIVEBI 14: DESTRUCTOR, CONSTRUCTOR, CONVERSION V DEBUGBI 15: AUTO_PTR, MUTABLE, VOLATILE V NH GI TC CHNG TRNH