Thursday, February 26, 2009

Basic Template Use in C++ for Dummies

Hi ...gyues.. if you don't now wat is template in c++ then here is some intresting thing for you...
and may be you will be loving it...., template & it's libarary is the feature of c++ which makes things easier... to solve and when u become familier with it you will loving Programming....
before you try it on your compiler... Turbo C dones't give any feature of template so you better to try this on GNU g++ you don't have it then don't worry here is the link. to download ...Download mingw gnu compiler
.................................
and you wish to write your code more easy and perfect way the here you can download codeblock Ide......
k...let start
let just make a function which will compare which one is max and which one is min
then...
//one munction for comparing the string as well as for interger you can use same for double and float...also...
#include<iostream >
using namespace std;
template < typename T > inline int Min(T a, T b) { return (b < a); }
int main()
{
cout <<Min(i,j)<<endl;
cout<<Min("hello","may")<<endl;
return 0;
}
hope you got the got...
use can use same thing in class formate also
template < class T > Hello
{
T t1;
void getT(t1 t)
{
//do you code according to the things t
}
};
now while creating the object use this formate
Hello < int > h;
Hello<double > h1;
Hello<string> h2;
so it will assign..the t accordingly...

now let come to the Libarary Part
vector
vector is the very good,it is something like dynamic array,you can insert,delete,element in the array without definning size and taking any counter for no of item in array, it will take care of all the things....eg:
vector<int > t;
t.push_back(2);
t.push_back(20);
t.push_back(14);
now t.size() will give you the size of the array
eg the current t.size()=3 //t contain tree element only
t.begin() will give pointer to first element ,and t.end() will give the pointer to the last element
and let letter on you wan't to sort the array then
u can use...
sort(t.begin(),t.end());
which will sort the element of array..
reverse(t.begin(),t.end());
to excess ith element in vector you can use directly like array t[i] ( will return the value of ith element in the vector)
Note:before using the above sort, reverse function you should include "#include<algorithm>" and "#include <vector>"

No comments:

Post a Comment