8
LAB 1 Introduction to C++ STL Objectives: 1. To learn about Standard Template Library. 2. To learn about Function Template and Class Template. 3. To solve problem by using STL in the solution. 1. Introduction The Standard Library is a fundamental part of the C++ Standard. It provides C++ programmers with a comprehensive set of efficiently implemented tools and facilities that can be used for most types of applications. In addition, the Standard Template Library (STL) is the most important section of the Standard Library. In order to fully understand about STL, basic language features of the C++, in particular, templates (both function templates and class templates) are important. In the following, brief explanation on function and class template will be highlighted. (NB: Students are encouraged to find more online information for advanced topic on STL) 2. Templates Templates are a way of making our classes more abstract by letting us define the behavior of the class without actually knowing what data type will be handled by the operations of the class. In essence, this is what is known as generic programming; this term is a useful way to think about templates because it helps remind the programmer that a templated class does not depend on the data type (or types) it deals with. Basically, a templated class is more focused on the algorithmic thought rather than the specific nuances of a single data type. Templates can be used in conjunction with abstract data types in order to allow them to handle any type of data. For example, you could make a templated stack class that can handle a stack of any data type, rather than having to create a stack class for every different data type for the stack to function. The ability to have a single class that can handle several different data types means the code is easier to maintain, and it makes classes more reusable.

LAB 1(1)

Embed Size (px)

DESCRIPTION

labbb

Citation preview

Page 1: LAB 1(1)

LAB 1Introduction to C++ STL

Objectives:

1. To learn about Standard Template Library.2. To learn about Function Template and Class Template.3. To solve problem by using STL in the solution.

1. Introduction

The Standard Library is a fundamental part of the C++ Standard. It provides C++ programmers with a comprehensive set of efficiently implemented tools and facilities that can be used for most types of applications. In addition, the Standard Template Library (STL) is the most important section of the Standard Library. In order to fully understand about STL, basic language features of the C++, in particular, templates (both function templates and class templates) are important. In the following, brief explanation on function and class template will be highlighted. (NB: Students are encouraged to find more online information for advanced topic on STL)

2. Templates

Templates are a way of making our classes more abstract by letting us define the behavior of the class without actually knowing what data type will be handled by the operations of the class. In essence, this is what is known as generic programming; this term is a useful way to think about templates because it helps remind the programmer that a templated class does not depend on the data type (or types) it deals with. Basically, a templated class is more focused on the algorithmic thought rather than the specific nuances of a single data type. Templates can be used in conjunction with abstract data types in order to allow them to handle any type of data. For example, you could make a templated stack class that can handle a stack of any data type, rather than having to create a stack class for every different data type for the stack to function. The ability to have a single class that can handle several different data types means the code is easier to maintain, and it makes classes more reusable.

2.1 Function Template

Overloaded functions normally perform similar or identical operations on different types of data. If the operations are identical for each type, they can be expressed more compactly and conveniently using function templates. Initially, the programmer writes a single function-template definition. Based on the argument types provided explicitly or inferred from calls to this function, the compiler generates separate object-code functions (i.e., function-template specializations) to handle each function call appropriately. In C, this task can be performed using macros created with the preprocessor directive #define (see Appendix F, Preprocessor). However, macros can have serious side effects and do not enable the compiler to perform type checking. Function templates provide a compact solution, like macros, but enable full type checking.

Page 2: LAB 1(1)

All function-template definitions begin with keyword template followed by a list of template parameters to the function template enclosed in angle brackets (< and >); each template parameter that represents a type must be preceded by either of the interchangeable keywords class or typename, as in any of the format below:

template< typename T > template< class ElementType > template< typename BorderType, typename FillType >

The type template parameters of a function-template definition are used to specify the types of the arguments to the function, to specify the return type of the function and to declare variables within the function. The function definition follows and appears like any other function definition. Note that keywords typename and class used to specify function-template parameters actually mean "any built-in type or user-defined type."

Example: Function Template printArray

Let us examine function template printArray in print_example.cpp, lines 8–15. Function template printArray declares (line 8) a single template parameter T (T can be any valid identifier) for the type of the array to be printed by function printArray; T is referred to as a type template parameter, or type parameter.

When the compiler detects a printArray function invocation in the client program (e.g., lines 30, 35 and 40), the compiler uses its overload resolution capabilities to find a definition of function printArray that best matches the function call. In this case, the only printArray function with the appropriate number of parameters is the printArray function template (lines 8–15). Consider the function call at line 30. The compiler compares the type of printArray's first argument (int * at line 30) to the printArray function template's first parameter (const T * at line 9) and deduces that replacing the type parameter T with int would make the argument match the parameter. Then, the compiler substitutes int for T throughout the template definition and compiles a printArray specialization that can display an array of int values. In print_example.cpp, the compiler creates three printArray specializations—one that expects an int array, one that expects a double array and one that expects a char array. For example, the function-template specialization for type int is:

void printArray( const int *array, int count ) {        for ( int i = 0; i < count; i++ )           cout << array[ i ] << " ";

       cout << endl; } // end function printArray

Page 3: LAB 1(1)

1   //print_example.cpp2   // Using template functions.3   #include <iostream>4   using std::cout;5   using std::endl;67   // function template printArray definition8   template< typename T>9   void printArray( const T *array, int count )10   {11      for ( int i = 0; i < count; i++ )12         cout << array[ i ] << " ";1314      cout << endl;15   } // end function template printArray1617   int main()18   {19      const int ACOUNT = 5; // size of array a20      const int BCOUNT = 7; // size of array b21      const int CCOUNT = 6; // size of array c2223      int a[ ACOUNT ] = { 1, 2, 3, 4, 5 };24      double b[ BCOUNT ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };25      char c[ CCOUNT ] = "HELLO"; // 6th position for null2627      cout << "Array a contains:" << endl;2829      // call integer function-template specialization30      printArray( a, ACOUNT );3132      cout << "Array b contains:" << endl;3334      // call double function-template specialization35      printArray( b, BCOUNT );3637      cout << "Array c contains:" << endl;3839      // call character function-template specialization40 printArray( c, CCOUNT );41      return 0;42      } // end main

Page 4: LAB 1(1)

2.2 Class Template

In general, you use a class template to define an abstract type whose behavior is generic and is reusable, adaptable.

Basic class

One constructor which initializes Data to 0, Set and Get methods, and a method to print current value. Usage is also quite simple:

Item item1;item1.SetData(120);item1.PrintData(); // Shows 120

class Item{ int Data;public: Item() : Data(0) {}

void SetData(int nValue) { Data = nValue; }

int GetData() const { return Data; }

void PrintData() { cout << Data; }};

Page 5: LAB 1(1)

Class Template

The usage of the above class template is:

(a) Item<int> item1;item1.SetData(120);item1.PrintData();

(b) Item<float> item2;float n = item2.GetData();

First instantiation with type int produces following methods:

Item<int>::Item() constructor SetData and PrintData methods for type int

Similarly, second instantiation with type float would produce:

Item<float>::Item() constructor GetData method for float type

template<class T> //template data type, Tclass Item{ T Data;public: Item() : Data( T() ) {}

void SetData(T nValue) { Data = nValue; }

T GetData() const { return Data; }

void PrintData() { cout << Data; }};

Page 6: LAB 1(1)

3. STL

STL has three key components, viz:1. Containers (vector, list, queue)2. Iterators3. Algorithms

The following code examples highlight the example of how these components are used. Study and observe the output of these codes to understand about STL components.

Example of C++ Code1. VectorTemplate.cpp2. ListTest.cpp

Page 7: LAB 1(1)

Lab Assignment: 1

An arithmetic sequence is a mathematical sequence consisting of a sequence in which the next term originates by adding a constant to its predecessor. When the first term x1 and the difference of the sequence d is known, the whole sequence is fixed, or in formula:

X n=x1+(n−1 ) d

(i.e. if x1=3, d=3, n=4: {3, 6, 9, 12})

By using STL containers and templates, write a program that stores the arithmetic sequence up until the nth number. The requirements of the program are:

Input: number of integers in the arithmetic sequence to be stored (n), first term (x1) and constant (d).Output: To display

a) The summation of all the numbers in the sequence.b) The value of stored in the list based on the index number given by the user, i.