CPP   44

lab

Guest on 11th May 2022 08:21:43 PM

  1. //////////////////////////////////////////////////////////////////////////////
  2. function template
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. template<class T>
  8.  
  9. T add(T &a,T &b)
  10.  
  11. {
  12.  
  13. T result = a+b;
  14.  
  15. return result;
  16.  
  17. }
  18.  
  19. int main()
  20.  
  21. {
  22.  
  23. int i =2;
  24.  
  25. int j =3;
  26.  
  27. float m = 2.3;
  28.  
  29. float n = 1.2;
  30.  
  31. cout<<"Addition of i and j is :"<<add(i,j);
  32. cout<<'\n';
  33.  
  34. cout<<"Addition of m and n is :"<<add(m
  35. ,n);
  36.  
  37. return 0;
  38.  
  39. }
  40.  
  41.  
  42. //////////////////////////////////////////////////////////////////////////////
  43.  
  44. #include <iostream>
  45.  
  46. using namespace std;
  47.  
  48. // This is a function template.
  49.  
  50. template <class X> void swapargs(X &a, X &b)
  51.  
  52. {
  53.  
  54. X temp;
  55.  
  56. temp = a;
  57.  
  58. a = b;
  59.  
  60. b = temp;
  61.  
  62. }
  63.  
  64. int main()
  65.  
  66. {
  67.  
  68. int i=10, j=20;
  69.  
  70. double x=10.1, y=23.3;
  71.  
  72. char a='x', b='z';
  73.  
  74. cout << "Original i, j: " << i << ' ' << j << '\n';
  75.  
  76. cout << "Original x, y: " << x << ' ' << y << '\n';
  77.  
  78. cout << "Original a, b: " << a << ' ' << b << '\n';
  79.  
  80. swapargs(i, j); // swap integers
  81.  
  82. swapargs(x, y); // swap floats
  83.  
  84. swapargs(a, b); // swap chars
  85.  
  86. cout << "Swapped i, j: " << i << ' ' << j << '\n';
  87.  
  88. cout << "Swapped x, y: " << x << ' ' << y <<
  89. '\n';
  90.  
  91. cout << "Swapped a, b: " << a << ' ' << b <<
  92. '\n';
  93.  
  94. return 0;
  95.  
  96. }
  97. ////////////////////////////////////////////////////////////////////////////////////////////
  98.  
  99. =============================================================================================
  100.    
  101.     function with two genric types
  102.    
  103.     #include <iostream>
  104.  
  105. using namespace std;
  106.  
  107. template <class type1, class type2>
  108.  
  109. void myfunc(type1 x, type2 y)
  110.  
  111. {
  112.  
  113. cout << x << ' ' << y << '\n';
  114.  
  115. }
  116.  
  117. int main()
  118.  
  119. {
  120.  
  121. myfunc(10, "I like C++");
  122.  
  123. myfunc(98.6, 19);
  124.  
  125. return 0;
  126.  
  127. }
  128.  
  129.  
  130. ================================================================================================================
  131.     Explicitly Overloading a Generic Function
  132.    
  133.    
  134.     // Overriding a template function.
  135.  
  136. #include <iostream>
  137.  
  138. using namespace std;
  139.  
  140. template <class X> void swapargs(X &a, X &b)
  141.  
  142. {
  143.  
  144. X temp;
  145.  
  146. temp = a;
  147.  
  148. a = b;
  149.  
  150. b = temp;
  151.  
  152. cout << "Inside template swapargs.\n";
  153.  
  154. }
  155.  
  156. // This overrides the generic version
  157.  
  158. //of swapargs() for ints.
  159.  
  160. void swapargs(int &a, int &b)
  161.  
  162. {
  163.  
  164. int temp;
  165.  
  166. temp = a;
  167.  
  168. a = b;
  169.  
  170. b = temp;
  171.  
  172. cout << "Inside swapargs int
  173. specialization.\n";
  174.  
  175. }
  176. int main()
  177.  
  178. {
  179.  
  180. int i=10, j=20;
  181.  
  182. double x=10.1, y=23.3;
  183.  
  184. char a='x', b='z';
  185.  
  186. cout << "Original i, j: " << i << ' ' << j << '\n';
  187.  
  188. cout << "Original x, y: " << x << ' ' << y << '\n';
  189.  
  190. cout << "Original a, b: " << a << ' ' << b <<'\n';
  191.  
  192. swapargs(i, j); // calls explicitly overloaded swapargs()
  193.  
  194. swapargs(x, y); // calls generic swapargs()
  195.  
  196. swapargs(a, b); // calls generic swapargs()
  197.  
  198. cout << "Swapped i, j: " << i << ' ' << j << '\n';
  199.  
  200. cout << "Swapped x, y: " << x << ' ' << y << '\n';
  201.  
  202. cout << "Swapped a, b: " << a << ' ' << b << '\n';
  203.  
  204. return 0;
  205.  
  206. }
  207. ========================================================================================================
  208.         Overloading a Function Template
  209.        
  210.        
  211.         // Overload a function template
  212. declaration.
  213.  
  214. #include <iostream>
  215.  
  216. using namespace std;
  217.  
  218. // First version of f() template.
  219.  
  220. template <class X>
  221.  
  222. void f(X a)
  223.  
  224. {
  225.  
  226. cout << "Inside f(X a)\n";
  227.  
  228. }
  229.  
  230. // Second version of f() template.
  231.  
  232. template <class X, class Y> void f(X a, Y b)
  233.  
  234. {
  235.  
  236. cout << "Inside f(X a, Y b)\n";
  237.  
  238. }
  239.  
  240. int main()
  241.  
  242. {
  243.  
  244. f(10);
  245.  
  246. // calls f(X)
  247.  
  248. f(10, 20); // calls f(X, Y)
  249.  
  250. return 0;
  251.  
  252. }
  253.  
  254.  
  255.  
  256. /========================================================================================        
  257.        
  258.         #include <iostream>
  259.  
  260. #include <cmath>
  261.  
  262. using namespace std;
  263.  
  264. void myfunc(int i)
  265.  
  266. {
  267.  
  268. cout << "value is: " << i << "\n";
  269.  
  270. }
  271.  
  272. void myfunc(double d)
  273.  
  274. {
  275.  
  276. double intpart;
  277.  
  278. double fracpart;
  279.  
  280. fracpart = modf(d, &intpart);
  281.  
  282. cout << "Fractional part: " << fracpart;
  283.  
  284. cout << "\n";
  285.  
  286. cout << "Integer part: " << intpart;
  287.  
  288. }
  289.  
  290. int main()
  291.  
  292. {
  293.  
  294. myfunc(1);
  295.  
  296. myfunc(12.2);
  297.  
  298. return 0;
  299.  
  300. }
  301.  
  302. Consider the overloaded functions in the following example program.
  303.  
  304. These functions could not be replaced by
  305.  
  306. a generic function because they do not do
  307. the same thing.
  308.         ========================================================================================================
  309.    
  310.     template <class myType>
  311.  
  312. myType max1(myType a, myType b)
  313.  
  314. { return (a>b?a:b); }
  315.  
  316. char* max1(char *a, char *b)
  317.  
  318. { if(strcmp(a,b)>0)
  319.  
  320. return a;
  321.  
  322. else
  323.  
  324. return b; }
  325.  
  326. Void main()
  327.  
  328. { cout<<max1(6,10);
  329.  
  330. Char s1[20],s2[25];
  331.  
  332. cout<<max1(s1,s2);
  333.  
  334. }
  335. ======================================================================================================================
  336.    
  337.    
  338.    
  339.     Multiple Arguments Function
  340. Templates
  341.  
  342.  
  343. #include <iostream>
  344.  
  345. #include <cstring>
  346.  
  347. using namespace std;
  348.  
  349. template <class T1, class T2, class T3>
  350.  
  351. void reverse(T1 x1, T2 x2, T3 x3 )
  352.  
  353. {
  354.  
  355. cout<<"original sequence"<<" "<<x1<<" "<<x2<<" "<<x3<<endl;
  356.  
  357. cout<<"reverse sequence"<<" "<<x3<<" "<<x2<<" "<<x1<<endl;
  358.  
  359. }
  360.  
  361. int main()
  362.  
  363. {
  364.  
  365. reverse(12, 34, 86);
  366.  
  367. reverse("JIIT","Best","university");
  368.  
  369. return 0;}
  370. ========================================================================================================================
  371.    
  372.    
  373.    
  374.     Member functions of Template class
  375.        
  376.         A member function of a template class is implicitly treated as a
  377. template function and it can have template arguments which are same
  378. as its class template arguments.
  379.    
  380.     template <class T>
  381.  
  382. class temp_stack
  383.  
  384. { void push(T a);
  385.  
  386. };
  387.  
  388. When defined outside:
  389.  
  390. template <class T>
  391.  
  392. Void temp_stack<T>::push(T a)
  393.  
  394. {
  395.  
  396. }
  397.    
  398.  ==================================================================================================================      
  399.        
  400.         CLASS TEMPLATE WITH MULTIPLE
  401. PARAMETERS
  402.  
  403.  
  404. #include <iostream>
  405.  
  406. using namespace std;
  407.  
  408. template<class T1, class T2>
  409.  
  410. class A
  411. {
  412. T1 a;
  413. T2 b;
  414. public:
  415. A(T1 x,T2 y)
  416. {
  417. a = x;
  418. b = y;
  419. }
  420. void display()
  421. {
  422. std::cout << "Values of a and b are : " << a<<" ,"<<b<<std::endl;
  423. }};
  424.  
  425.  
  426. ================================================================================================================
  427.    
  428.     #include <iostream>
  429.  
  430. using namespace std;
  431.  
  432. template<class T, int size>
  433.  
  434. class A
  435. {
  436. public:
  437. T arr[size];
  438. void insert()
  439. {int i =1;
  440. for (int j=0;j<size;j++)
  441. {
  442. arr[j] = i;
  443. i++;
  444. }}
  445. void display()
  446. {
  447. for(int i=0;i<size;i++)
  448. {
  449. std::cout << arr[i] << " ";
  450. }}
  451.  
  452. };
  453. int main()
  454. {
  455. A<int,10> t1;
  456. t1.insert();
  457. t1.display();
  458. return 0;
  459. }
  460.  
  461. ==========================================================================================================================
  462.    
  463.    
  464.     For Example, consider we have a template class ‘myIncrement’ which has a constructor to initialize a value and a template function toIncrement that increments the value by 1.
  465.  
  466. This particular class will work perfectly for all the data types except for char. Instead of incrementing the value for char, why not give it a special behavior and convert the character to uppercase instead?
  467.  
  468. In order to do this, we can go for template specialization for the char data type.
  469.  
  470. This implementation is shown in the below code Exampl#include <iostream>
  471. am>
  472. using namespace std// class template:
  473. te:
  474. template <class T>
  475. class myIncrement {
  476.   T value;
  477.   public:
  478.   myIncrement (T arg) {value=arg;}
  479.   T toIncrement () {return ++value;}// class template specialization:
  480. on:
  481. template <>
  482. class myIncrement <char> {
  483.    char value;
  484.   public:
  485.    myIncrement (char arg) {value=arg;}
  486.    char uppercase ()
  487.   {
  488.     if ((value>='a')&&(value<='z'))
  489.     value+='a'-'a';
  490.     return value;
  491.   }
  492. };
  493. int main () {
  494.   myIncrement<int> myint (7);
  495.   myIncrement<char> mychar ('s');
  496.   myIncrement<double> mydouble(11.0);
  497.  
  498.   cout<<"Incremented int value: "<< myint.toIncrement()<< endl;
  499.   cout<<"Uppercase value: "<<mychar.uppercase()<< endl;
  500.   cout<<"Incremented double value: "<<mydouble.toIncrement()<< endl;
  501.   return 0;
  502. }
  503.   //////////////////////////////////////////////////////////////////////////////////=====
  504. ===
  505. =====================================================================================
  506.    
  507.     ht//vulms.vu.edu.pk/Courses/CS304/Downloads/CS304_Handouts%20(Updated).pdf
  508. pdf
  509. ht//quizxp.com/programming-in-c-plus-plus/
  510. us/
  511. ======================================================================================
  512.    
  513.     / Min/Max Templa#include<iostream>
  514. #include <string>
  515. ng>
  516. using namespace std// Template for the min function
  517. ion
  518.  
  519. template <class T>
  520. T min(T number1, T number2)
  521. {
  522.    return (number1 < number2)? number1 : number2;
  523. // Template for the max function
  524. ion
  525.  
  526. template <class T>
  527. T max(T number1, T number2)
  528. {
  529.    return (number1 > number2)? number1 : number2;
  530. // The main function
  531. ion
  532.  
  533. int main()
  534. {// Test min and max with int arguments.
  535. ts.
  536.    int num1 = 5;
  537.    int num2 = 3;
  538.    cout << "minimum of 5, 3 is:  " ;
  539.    cout << min(num1, num2) << endl;
  540.    cout << "maximum of 5, 3 is:  " ;
  541.    cout << max(num1, num2) << endl;
  542.  // Test min and max with double arguments.
  543. ts.
  544.    double num3 = 5.5;
  545.    double num4 = 3.5;
  546.    cout << "minimum of 5.5, 3.5 is:  " ;
  547.    cout << min(num3, num4) << endl;
  548.    cout << "maximum of 5.5, 3.5 is:  " ;
  549.    cout << max(num3, num4) << endl;
  550.  // Test min and max with string arguments.
  551. ts.
  552.    string hello = "hello";
  553.    string hi = "hi";
  554.    cout << "minimum of \"hello\" and \" is: "s: ";
  555.    cout << min(hello, hi) << endl;
  556.    cout << "maximum of \"hello\" and \" is: "s: ";
  557.    cout << max(hello, hi) << endl;
  558.  
  559.    return 0;
  560. }
  561.     ====================================================================================================================
  562.         ================================================
  563.         ====================================================================
  564.         ==================================================// A Generic bubble sort.
  565. #include <iostream>
  566. am>
  567. using namespace std;
  568. template <class X> void bubble(
  569. X *ite// pointer to array to be sorted
  570. ted
  571. int cou// number of items in array
  572. ray
  573. {
  574. register int a, b;
  575. X t;
  576. for(a=1; a<count; a++)
  577. for(b=count-1; b>=a; b--)
  578. if(items[b-1] > items[b]// exchange elements
  579. nts
  580. t = items[b-1];
  581. items[b-1] = items[b];
  582. items[b] = t;
  583. }
  584. }
  585. int main()
  586. {
  587. int iarray[7] = {7, 5, 4, 3, 9, 8, 6};
  588. double darray[5] = {4.3, 2.5, -0.9, 100.2, 3.0};
  589. int i;
  590. cout << "Here is unsorted integer array: ";
  591. for(i=0; i<7; i++)
  592. cout << iarray[i] << ' ';
  593. cout << endl;
  594. cout << "Here is unsorted double array: ";
  595. for(i=0; i<5; i++)
  596. cout << darray[i] << ' ';
  597. cout << endl;
  598. bubble(iarray, 7);
  599. bubble(darray, 5);
  600. cout << "Here is sorted integer array: ";
  601. for(i=0; i<7; i++)
  602. cout << iarray[i] << ' ';
  603. cout << endl;
  604. cout << "Here is sorted double array: ";
  605. for(i=0; i<5; i++)
  606. cout << darray[i] << ' ';
  607. cout << endl;
  608. return 0;
  609. }
  610.         ======================================================================================================================
  611.             ====================    compacting an array
  612.             ================================================================================
  613.            
  614.            
  615.            
  616.            
  617.            
  618.         // A Generic array compaction function.
  619. #include <iostream>
  620. am>
  621. using namespace std;
  622. template <class X> void compact(
  623. X *ite// pointer to array to be compacted
  624. ted
  625. int cou// number of items in array
  626. ray
  627. int sta// starting index of compacted region
  628. ion
  629. int e// ending index of compacted region
  630. ion
  631. {
  632. register int i;
  633. for(i=end+1; i<count; i++, start++)
  634. items[start] = items[/* For the sake of illustration, the remainder of
  635. the array will be zeroed. */. */
  636. for( ; start<count; start++) items[start] = (X) 0;
  637. }
  638. int main()
  639. {
  640. int nums[7] = {0, 1, 2, 3, 4, 5, 6};
  641. char str[18] = "Generic Functions";
  642. int i;
  643. cout << "Here is uncompacted integer array: ";
  644. for(i=0; i<7; i++)
  645. cout << nums[i] << ' ';
  646. cout << endl;
  647. cout << "Here is uncompacted string: ";
  648. for(i=0; i<18; i++)
  649. Chapter 18: Templates 471 C++
  650. cout << str[i] << ' ';
  651. cout << endl;
  652. compact(nums, 7, 2, 4);
  653. compact(str, 18, 6, 10);
  654. cout << "Here is compacted integer array: ";
  655. for(i=0; i<7; i++)
  656. cout << nums[i] << ' ';
  657. cout << endl;
  658. cout << "Here is compacted string: ";
  659. for(i=0; i<18; i++)
  660. cout << str[i] << ' ';
  661. cout << endl;
  662. return 0;
  663. }
  664.  
  665. ======================================================================================================================
  666.     ==========================================
  667.    
  668.     stackssss
  669.    
  670.    
  671. // This function demonstrates a generic stack.
  672. #include <iostream>
  673. am>
  674. using namespace std;
  675. const int SIZE = // Create a generic stack class
  676. ass
  677. template <class StackType> class stack {
  678. StackType stck[SIZ// holds the stack
  679. ack
  680. int t// index of top-of-stack
  681. ack
  682. public:
  683. stack() { tos = 0// initialize stack
  684. ack
  685. void push(StackType o// push object on stack
  686. ack
  687. 474 C++: The Complete Reference
  688. StackType pop// pop object from stack
  689. ack// Push an object.
  690. ct.
  691. template <class StackType> void stack<StackType>::push(StackType ob)
  692. {
  693. if(tos==SIZE) {
  694. cout << "Stack is full.\n";
  695. return;
  696. }
  697. stck[tos] = ob;
  698. tos++// Pop an object.
  699. ct.
  700. template <class StackType> StackType stack<StackType>::pop()
  701. {
  702. if(tos==0) {
  703. cout << "Stack is empty.\n";
  704. return// return null on empty stack
  705. ack
  706. }
  707. tos--;
  708. return stck[tos];
  709. }
  710. int main(// Demonstrate character stacks.
  711. ks.
  712. stack<char> s1, // create two character stacks
  713. cks
  714. int i;
  715. s1.push('a');
  716. s2.push('x');
  717. s1.push('b');
  718. s2.push('y');
  719. s1.push('c');
  720. s2.push('z');
  721. for(i=0; i<3; i++) cout << "Pop s1: " << s1.pop() << "\n";
  722. for(i=0; i<3; i++) cout << "Pop s2: " << s2.pop() << "\// demonstrate double stacks
  723. cks
  724. stack<double> ds1, d// create two double stacks
  725. cks
  726. Chapter 18: Templates 475 C++
  727. ds1.push(1.1);
  728. ds2.push(2.2);
  729. ds1.push(3.3);
  730. ds2.push(4.4);
  731. ds1.push(5.5);
  732. ds2.push(6.6);
  733. for(i=0; i<3; i++) cout << "Pop ds1: " << ds1.pop() << "\n";
  734. for(i=0; i<3; i++) cout << "Pop ds2: " << ds2.pop() << "\n";
  735. return 0;
  736. }
  737.    
  738.  
  739. ============================================================================================================================
  740.     =================================================genric safe array
  741.    
  742.     =======================================================================// A generic safe array example.
  743. #include <iostream>
  744. #include <cstdlib>
  745. ib>
  746. using namespace std;
  747. const int SIZE = 10;
  748. template <class AType> class atype {
  749. AType a[SIZE];
  750. public:
  751. atype() {
  752. register int i;
  753. for(i=0; i<SIZE; i++) a[i] = i;
  754. }
  755. AType &operator[](int i);// Provide range checking for atype.
  756. pe.
  757. template <class AType> AType &atype<AType>::operator[](int i)
  758. {
  759. if(i<0 || i> SIZE-1) {
  760. cout << "\nIndex value of ";
  761. cout << i << " is out-of-bounds.\n";
  762. exit(1);
  763. }
  764. return a[i];
  765. }
  766. int main()
  767. {
  768. atype<int> int// integer array
  769. ray
  770. atype<double> double// double array
  771. ray
  772. int i;
  773. cout << "Integer array: ";
  774. for(i=0; i<SIZE; i++) intob[i] = i;
  775. for(i=0; i<SIZE; i++) cout << intob[i] << " ";
  776. cout << '\n';
  777. cout << "Double array: ";
  778. for(i=0; i<SIZE; i++) doubleob[i] = (double) i/3;
  779. for(i=0; i<SIZE; i++) cout << doubleob[i] << " ";
  780. cout << '\n';
  781. intob[12] = 1// generates runtime error
  782. ror
  783. return 0;
  784. }
  785.  
  786. ===========================================================================================================================
  787.     =============================================================
  788.    
  789.    
  790.    
  791.     template <class T>
  792. class Complx {
  793. private:
  794.         T real, imag;
  795. public:
  796.         Complx(T&, T&);
  797.         T& getReal();
  798.         T& getImag();
  799. };
  800.  
  801. template <class T>
  802. Complx<T>::Complx(T& a, T& b) {
  803.         real = a;
  804.         imag = b;
  805. }
  806.  
  807. template <class T>
  808. T& Complx<T>::getReal() {
  809.         return real;
  810. }
  811.  
  812. template <class T>
  813. T& Complx<T>::getImag() {
  814.         return imag;#include <iostream>
  815. am>
  816.  
  817. int main()
  818. {
  819.         double i=100, j=200;
  820.         Complx <double> myComplx(i,j);
  821.  
  822.         std::cout <<"My complex is " << myComplx.getReal() << ","
  823.                 << myComplx.getImag() << std::endl;
  824. }
  825.  
  826. ============================================================================================================================
  827.     =============================================================================
  828.    
  829.    
  830.    
  831. // Demonstrate non-type template arguments.
  832. #include <iostream>
  833. #include <cstdlib>
  834. ib>
  835. using namespace s// Here, int size is a non-type argument.
  836. nt.
  837. template <class AType, int size> class atype {
  838. AType a[siz// length of array is passed in size
  839. ize
  840. public:
  841. atype() {
  842. register int i;
  843. for(i=0; i<size; i++) a[i] = i;
  844. }
  845. AType &operator[](int i);// Provide range checking for atype.
  846. pe.
  847. template <class AType, int size>
  848. AType &atype<AType, size>::operator[](int i)
  849. {
  850. if(i<0 || i> size-1) {
  851. cout << "\nIndex value of ";
  852. cout << i << " is out-of-bounds.\n";
  853. exit(1);
  854. }
  855. return a[i];
  856. }
  857. int main()
  858. {
  859. atype<int, 10> int// integer array of size 10
  860.  10
  861. atype<double, 15> double// double array of size 15
  862.  15
  863. int i;
  864. cout << "Integer array: ";
  865. for(i=0; i<10; i++) intob[i] = i;
  866. for(i=0; i<10; i++) cout << intob[i] << " ";
  867. cout << '\n';
  868. cout << "Double array: ";
  869. for(i=0; i<15; i++) doubleob[i] = (double) i/3;
  870. for(i=0; i<15; i++) cout << doubleob[i] << " ";
  871. cout << '\n';
  872. intob[12] = 1// generates runtime error
  873. ror
  874. return 0;
  875. }
  876. ====================================================================================================================
  877.     template <> wala haiyeh
  878.    
  879.    
  880. // Demonstrate class specialization.
  881. #include <iostream>
  882. am>
  883. using namespace std;
  884. template <class T> class myclass {
  885. T x;
  886. public:
  887. myclass(T a) {
  888. cout << "Inside generic myclass\n";
  889. x = a;
  890. }
  891. T getx() { return x; }// Explicit specialization for int.
  892. nt.
  893. template <> class myclass<int> {
  894. int x;
  895. public:
  896. myclass(int a) {
  897. cout << "Inside myclass<int> specialization\n";
  898. x = a * a;
  899. }
  900. int getx() { return x; }
  901. };
  902. int main()
  903. {
  904. myclass<double> d(10.1);
  905. cout << "double: " << d.getx() << "\n\n";
  906. myclass<int> i(5);
  907.  
  908. cout << "int: " << i.getx() << "\n";
  909. return

Raw Paste


Login or Register to edit or fork this paste. It's free.