CP II Labs Till 22March 2024
CP II Labs Till 22March 2024
CP II Labs Till 22March 2024
Week 02:
Basics of Classes, Objects, Data Structures
Functions Division:
For larger programs
make programs more comprehensible
function has:
a clearly defined purpose and
a clearly defined interface to the other functions
Modules
Grouping a number of functions together into a larger entity called
a module
Structured Programming:
Dividing a program into functions and modules is the cornerstones
of structured programming
As programs grow larger and more complex, even the structured
programming approach begins to become excessively complicated.
Categories in STL:
Sets: Store objects with keys; only one instance of each key is allowed.
Maps: Store pairs where the first part is an object containing a key, and the
second part is an object containing a value.
Multisets and Multimaps: Relax the restriction of allowing only one instance
of each key.
Difference: unordered ones do not maintain their keys in sorted order.
Sets and Multisets
Maps & Multimaps
Stores pairs.
A pair consists of a key object and a value object.
The key object contains the key to be searched for.
The value object contains additional data associated with the key.
Keys can be strings, numbers, or objects of complex classes.
Values can be strings, numbers, objects, or even containers.
Example applications include:
A frequency table where the key is a word and the value is the
frequency of that word in a document.
An index where the key is a word, and the value is a list of page
numbers.
An ordinary dictionary where keys are words, and values are their
definitions.
An Associative Array
Task
Make a map data structure with following requirements:
Elements of the pair
Key Student registration
Object structure of (1) Name, (2) Session (3) CGPA)
Week 3 (Lab 6)
Container Adapters
Special-purpose containers from the normal containers mentioned
previously using a construct called container adapters.
The specialized containers implemented with container adapters
in the STL are stacks, queues, and priority queues.
a stack restricts access to pushing and popping a data item on and off the top of
the stack.
In a queue, you push items at one end and pop them off the other.
In a priority queue, you push data in the front in random order, but when you pop
the data off the other end, you always pop the largest item stored: the priority
queue automatically sorts the data or you
Stacks
Stack Class:
Defined in header <stack>.
Enables insertions and deletions at one end, called the top.
Known as a last-in, first-out (LIFO) data structure.
Function-Call Stack:
Introduced in the context of function-call stacks in Section 6.11.
Underlying Data Structures:
Can be implemented using vector, list, or deque.
By default, implemented with a deque.
Stack Operations:
push: Inserts an element at the top of the stack. Uses push_back
of the underlying container.
pop: Removes the top element of the stack. Uses pop_back of
the underlying container.
top: Gets a reference to the top element. Uses back of the
underlying container.
empty: Checks if the stack is empty. Uses empty of the
underlying container.
size: Returns the number of elements in the stack. Uses size of
the underlying container.
Queue
Queue Class:
Defined in header <queue>.
Operates as a first-in, first-out (FIFO) data structure.
Underlying Data Structures:
Can use the Standard Library’s list or deque containers.
By default, implemented with a deque
Queue Operations:
push: Inserts an element at the back of the queue. Uses
push_back of the underlying container.
pop: Removes the element at the front of the queue. Uses
pop_front of the underlying container.
front: Gets a reference to the first element in the queue. Uses
front of the underlying container.
back: Gets a reference to the last element in the queue. Uses
back of the underlying container.
empty: Checks if the queue is empty. Calls empty on the
underlying container.
size: Returns the number of elements in the queue. Calls size on
the underlying container.
Priority Queues
Priority Queue Class:
Defined in header <queue>.
Default Underlying Data Structure:
Elements are stored in a vector.
Behavior and Ordering:
Inserts elements in sorted priority order.
The highest-priority element (largest value) is at the front.
Heap Structure:
Elements arranged in a heap to maintain highest-priority
element at the front.
Default Comparator:
Uses less<T> for comparing elements, but can be customized.
Priority Queue Operations:
push: Inserts an element in priority order, then reorders
elements.
pop: Removes the highest-priority element.
top: Gets a reference to the top element (using front of the
underlying container).
empty: Determines if the queue is empty (using empty of the
underlying container).
size: Gets the number of elements (using size of the underlying
container).
Week4
Data Structures: Arrays & Vectors
Data structures:
Collections of related data items
Arrays:
Fixed-size collections of data items of same type (int, float)
To use C++ STL template <array> header is included
Vectors:
Collections that can grow and shrink dynamically at execution
time.
To use C++ STL template <vector> header is included
Arrays:
The data items can be simple types such as int or float, or
Can be user-defined types such as structures and objects.
To refer to a particular location in the array,
Name of array and the position number (in square bracket) is
specified E.g. age[1], age[2]
Position number is called subscript or index
Pronounced as “age sub one”
Subscript must be an integer or integer expression
Declaring arrays
Specify type of the elements and the number of elements
required
Notation:
array <type, arraySize> arrayName;
array <int, 12> age;
It indicates that array is a class template.
Declaration reserves memory
arraySize must be an unsigned integer
Examples using Arrays
Declare, initialize, and manipulate
Declaring array and initializing using a loop
Initializing in a declaration with an initializer list
Notation:
C++ library function “Sort”
Searching:
The process of finding a particular element of an array is called
searching.
Notation:
C++ library function “binary_search”
Example
Multidimensional Array
tables of values consisting of information arranged in rows and
columns
Example
Range based for loop
for (auto const& row : a)
Explanation page (948, 340)
auto keyword
Infer variable’s data type based on
variable’s initializer value
Another way:
total = 0;
for (auto row : a) { // for each row
for (auto column : row) { // for
each column in row
total += column;
}
}
Function Overloading
C++ enables several functions of the same name to be
defined, as-long-as they have different signatures. This is
called function overloading
Function overloading is used to create several functions of the
same name that perform similar tasks, but on different data
types.
For example, many functions in the math library are
overloaded for different numeric types
float , double and long double
Example
How compiler Differentiates
Overloaded functions are distinguished by their signatures.
A signature is a combination of a function’s name and its
parameter types (in order).
Custom Templates
Function templates enable you to conveniently specify a
variety of overloaded functions—called function-
template specializations.
Class templates enable you to conveniently specify a variety
of related classes—called class-template specializations.
Programming with templates is also known as generic
programming.
Custom Templates
Let's understand it using the concept of a stack independent
of the type of the items being placed in the stack
To instantiate a stack, a data type must be specified
Here, we define a stack generically then use type-specific
versions of this generic stack class
One Stack class template, could become the basis for creating
many Stack class template specializations (such as “ Stack of double
s,” “ Stack of int s,” “ Stack of Employee s,” “ Stack of Bill s,” “ Stack of Activation
Record s,” etc.) used in a program.
Class Template Stack<T>
The Stack class-template definition looks like a conventional
class definition, with a few key differences. First, it’s
preceded by
template<typename T>
keyword template
followed by list of parameters in angle brackets (< and >);
interchangeable keywords typename or class
T acts as a placeholder for the Stack ’s element type.
`
Class Template Stack<T> ’s
Data Representation
A stack requires insertions and deletions only at its
top
a vector or a deque could be used to store the
stack ’s elements
A deque supports fast insertions and deletions at its
front and its back.
A deque is default representation for the Standard
Library’s stack adapter because a deque grows
more efficiently than a vector
Member functions of Class
top (lines 11–13) returns a const reference to the Stack ’s
top element.
push (lines 16–18) places a new element on the top of the
Stack .
pop (lines 21–23) removes the Stack ’s top element.
isEmpty (lines 26–28) returns a bool value— true if the
Stack is empty and false otherwise.
size (lines 31–33) returns the number if elements in the Stack
.
Testing Class Template Stack<T>
Function Template to Manipulate a Class-
Template Specialization Object
Function template testStack (lines 10–36) to perform the
same tasks as main in Fig. 18.3
Basic concepts of OOP
Classes and Object: (a review)
Lets begin with an example which demonstrates the syntax
and general features of classes in C++
Code Explanation
Program contains
A class
has One data member and two member functions
two objects of that class (created in the main function)
Class definition (or specifier):
Keyword “class” followed by class name “smallobj”
Class name capitalization style:
Pascal case: SmallObj
Camel case: smallObj
Class body:
Pair of left and right braces as {and}
Terminated with semicolon as ;
Key words
Access Specifiers
Public:
Member function or data member can be called or accessed by other
functions in the program (such as main) and by member functions of
other classes.
Private:
Data or functions can only be accessed from within the class.
Always followed by colon (:)
Void to the left of a function
Function will not return any data to its call task
Main Idea in OOP
Placing data and functions together into a single entity is a
central idea in object-oriented programming.
Private and Public
Two unfamiliar keywords: private and
public
A key feature of OOP:
data hiding:
data is concealed within a class so that it cannot
be accessed mistakenly by functions outside the
class
Private:
data or functions can only be accessed from
within the class
Public:
data or functions, on the other hand, are
accessible from outside the class
Instructor:
Muhammad Usman
Objectives
Introduction
Base and derived classes
Relationship between base & derived classes
Constructor & destructors in derived classes
Public, protected & private inheritance
Introduction
Inheritance is an essential part of OOP.
Big payoff permits code reusability.
Once base class is written, it need not be touched again
Reusing existing code saves time and money
existing class base class, new class derived class
derived class inherits members of base class
C++ offers public, protected and private inheritance
Public inheritance:
every object of a derived class is also an object of that derived
class’s base class
For example: base class vehicle and car as derived class
All cars are vehicle and but not all vehicles are cars
Is-a-relationship / has-a-relationship
Is-a-relationship:
an object of a derived class also can be treated as an object of its
base class
for example, a Car is a Vehicle , so any attributes and behaviors
of a Vehicle are also attributes and behaviors of a Car
Has-a-relationship:
an object contains one or more objects of other classes as
members
For example, a Car has many components—it has a steering
wheel, has a brake pedal, has a transmission, etc
Specifying the Derived Class
Instructor:
Muhammad Usman
Public and Private Inheritance
With declarations like
class manager : public employee
The keyword public specifies that objects of the derived
class are able to access public member functions of the base
class.
When keyword private is used, objects of the derived
class cannot access public member functions of the base class.
So no member of the base class is accessible to objects of the
derived class
When to use?
Sometimes, the derived class is created as a way of
completely modifying the operation of the base class, hiding
or disguising its original interface.
You might derive Stack from Array, but you wouldn’t want
the users of Stack objects to treat them as if they were arrays,
using the [] operator to access data items, for example.
Objects of Stack should always be treated as if they were
stacks, using push() and pop().
Multiple Inheritance
A class can be derived from more than one base class.
Abstraction in C++
Abstraction means displaying only essential information and
hiding the details.
Data abstraction refers to providing only essential
information about the data to the outside world, hiding the
background details or implementation.
Abstraction using Classes:
Class helps us to group data members and member functions
using available access specifiers
Members declared as public in a class, can be accessed from
anywhere in the program.
Members declared as private in a class, can be accessed only
from within the class.
Abstraction in Header files:
One more type of abstraction in C++ can be header files
For example, consider the pow() method present in math.h
header file.
Encapsulation in C++
Encapsulation is a process of combining data members and
functions in a single unit called class.
This is to prevent the access to the data directly, the access to
them is provided through the functions of the class.
It is one of the popular feature of Object-Oriented
Programming(OOPs) that helps in data hiding.
Week 6
Computer Programming-II
(1: Linked Lists, Trees, Graphs)
Instructor:
Muhammad Usman
Self-Referential Classes (Ch 19)
A self-referential class objects contains a member that points to a class object of the
same class type.
it can be linked together to form useful data structures such as linked lists and trees.
Member nextPtr is referred to as a link—i.e.,
nextPtr can “tie” an object of type Node to another object of the same type
Member functions
A constructor that receives an integer to initialize member data
A setData function to set the value of member data
A getData function to return the value of member data ,
A setNextPtr function to set the value of member nextPtr
A getNextPtr function to return the value of member nextPtr
// Assign to head
// Node class to represent if (head == NULL) {
// a node of the linked list. head = newNode;
classNode { return;
public: }
intdata;
Node* next; // Traverse till end of list
Node* temp = head;
while (temp->next != NULL) {
// Default constructor
Node() // Update temp
{ temp = temp->next;
data = 0; }
next = NULL;
} // Insert at the last.
temp->next = newNode;
}
// Parameterised Constructor
Node(intdata) // Function to print the
{ // nodes of the linked list.
this->data = data; void printList()
this->next = NULL; {
} Node* temp = head;
};
// Check for empty list.
if (head == NULL) {
// Linked list class to cout << "List empty" << endl;
// implement a linked list. return;
classLinkedlist { }
Node* head;
// Traverse the list.
while (temp != NULL) {
public:
cout << temp->data << " ";
// Default constructor temp = temp->next;
Linkedlist() { head = NULL; } }
}
};
int main()
{
Linkedlist list;
// Inserting nodes
list.insertNode(1);
list.insertNode(2);
list.insertNode(3);
list.insertNode(4);
Doubly Circular
Trees
A tree is a nonlinear, two-dimensional data structure.
Tree nodes contain two or more links.
Binary trees: trees whose nodes all contain two links (none, one or
both of which may have the value nullptr).
Basic Terminology
The root node (node B ) is the first node in a tree.
Each link in the root node refers to a child (nodes A and D ).
The left child (node A ) is the root node of the left subtree (which contains only node
A ), and the right child (node D ) is the root node of the right subtree (which
contains nodes D and C ).
The children of a given node are called siblings (e.g., nodes A and D are siblings). A
node with no children is a leaf node (e.g., nodes A and C are leaf nodes).
Binary Search Trees
Binary search tree
values in left subtree are less than value in its parent node
values in right subtree are greater than value in its parent node.
Tree Traversals (Inorder, Preorder and Postorder)
Unlike linear data structures (Array, Linked List, Queues,
Stacks, etc) which have only one logical way to traverse
them, trees can be traversed in different ways.