VIMP OOP
VIMP OOP
1. Explain need of operator overloading. What are the rules to be followed when overloading
an operator in C++?
ANS: Need of Operator Overloading in C++
Make Custom Types Work Like Built-In Types:
For example, if you define a Complex number class, you may want to use + to add two
complex numbers just like you do with int.
Improve Code Readability and Clarity:
Instead of calling a member function like c1.add(c2), you can write c1 + c2, which is easier to
read and write.
Enable Natural Syntax for Custom Classes:
Especially useful in classes that represent:
o Complex numbers
o Vectors
o Matrices
o Fractions
o Strings
o File streams
o Iterators
Increase Code Reusability:
Overloaded operators make code more modular and object-oriented by reusing the same
operator for different object behaviors.
Rules for Operator Overloading in C++
While overloading operators in C++, the following rules must be followed:
Rule
Rule Description
No.
1 Only existing C++ operators can be overloaded. You cannot create new operators.
At least one operand must be a user-defined type (e.g., a class or struct). You cannot
2
overload operators for only built-in types.
3 You cannot change the precedence, associativity, or arity of operators.
Certain operators cannot be overloaded, such as: ::, ., .*, sizeof, ?:, typeid, and the cast
4
operators like static_cast.
Overloaded operators should behave logically and intuitively, matching their expected use.
5
For example, + should add, not subtract.
6 You can overload an operator either as a member function or a friend function.
For assignment (=), function call (()), subscript ([]), and member access (->) — must be
7
overloaded as member functions only.
2. How virtual functions are implemented in C++? Explain with help of a program.
ANS: virtual functions allow runtime polymorphism, enabling the correct function to be called based
on the object type (not pointer/reference type).
Behind the scenes, C++ uses a mechanism called the vtable (virtual table) to implement virtual
functions.
How It Works Internally:
1. vtable (Virtual Table):
o A table of function pointers maintained per class.
o Contains addresses of the virtual functions that can be called on an object of that
class.
2. vptr (Virtual Pointer):
o Each object of a class with virtual functions contains a hidden pointer (vptr) pointing
to the class's vtable.
3. Runtime Decision:
o When a virtual function is called using a base class pointer, the vptr helps decide
which version of the function (base or derived) to call at runtime.
� Example Program:
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "Base class show() function" << endl;
}
};
int main() {
Base* bptr;
Derived d;
return 0;
}
� Output:
Derived class show() function
3. Define a class string and use binary overloaded operator (= =) to compare two strings
ANS: #include <iostream>
#include <cstring> // For strcmp()
using namespace std;
class MyString {
char str[100];
public:
// Constructor
MyString(const char* s = "") {
strcpy(str, s);
}
// Overload == operator
bool operator==(MyString& s) {
return strcmp(str, s.str) == 0;
}
// Display function
void display() {
cout << str << endl;
}
};
int main() {
MyString s1("hello");
MyString s2("hello");
MyString s3("world");
if (s1 == s2)
cout << "s1 and s2 are equal." << endl;
else
cout << "s1 and s2 are not equal." << endl;
if (s1 == s3)
cout << "s1 and s3 are equal." << endl;
else
cout << "s1 and s3 are not equal." << endl;
return 0;
}
Output:
s1 and s2 are equal.
s1 and s3 are not equal.
4. Explain what is type conversions? Define implicit type casting and explicit type casting
with example.
ANS: Type conversion is the process of converting a value from one data type to another. It occurs
when different data types are mixed in an expression or when a value is assigned to a variable of a
different type.
There are two types of type conversions in C++:
1. Implicit Type Casting (Type Promotion)
2. Explicit Type Casting (Type Casting by the Programmer)
int main() {
int a = 10;
float b;
int main() {
float x = 10.75;
int y;
#include <iostream>
using namespace std;
class Base {
public:
~Base() {
cout << "Base destructor called" << endl;
}
};
int main() {
Base* ptr = new Derived(); // Base pointer to Derived object
delete ptr; // Only Base destructor is called
return 0;
}
Output:
Base destructor called
Only base destructor is called. Derived destructor is skipped.
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {
cout << "Base destructor called" << endl;
}
};
6. Write a C++ program to overload binary operator ‘+’ to add two complex numbers using
member function and friend function
ANS:
1. Using Member Function
#include <iostream>
using namespace std;
class Complex {
float real, imag;
public:
Complex(float r = 0, float i = 0) {
real = r;
imag = i;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3.5, 2.5), c2(1.5, 4.5), c3;
c3 = c1 + c2;
return 0;
}
2. Using Friend Function
#include <iostream>
using namespace std;
class Complex {
float real, imag;
public:
Complex(float r = 0, float i = 0) {
real = r;
imag = i;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(5, 6), c2(2, 3), c3;
c3 = c1 + c2;
return 0;
}
Output for Both:
Sum: 6 + 7i
#include <iostream>
using namespace std;
class Print {
public:
void show(int a) {
cout << "Integer: " << a << endl;
}
void show(float b) {
cout << "Float: " << b << endl;
}
};
int main() {
Print obj;
obj.show(5);
obj.show(3.14f);
return 0;
}
� Example: Operator Overloading
#include <iostream>
using namespace std;
class Base {
public:
virtual void display() {
cout << "Base display" << endl;
}
};
int main() {
Base* ptr;
Derived d;
ptr = &d;
ptr->display(); //�Calls�Derived’s�display()�at�runtime
return 0;
}
� Output:
Derived display
8. How do you declare and define a pure virtual function in C++? Explain with help of a
program
ANS: A pure virtual function is a function that has no definition in the base class and must be
implemented by any derived class. It is declared by assigning = 0 at the end of the function
declaration in the base class. A class containing at least one pure virtual function is called an abstract
class, and objects of an abstract class cannot be instantiated directly.
� Syntax:
virtual return_type function_name(parameters) = 0;
#include <iostream>
using namespace std;
// Regular function
void display() {
cout << "This is a shape." << endl;
}
};
// Derived class that must implement draw() due to pure virtual function in base class
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a Circle" << endl;
}
};
int main() {
// Shape s; // Error: Cannot instantiate abstract class
delete shape1;
delete shape2;
return 0;
}
� Output:
Drawing a Circle
Drawing a Rectangle
class AbstractClass {
public:
virtual void someFunction() = 0; // Pure virtual function
};
= 0 denotes that the function is pure virtual.
A class with at least one pure virtual function is considered an abstract class.
#include <iostream>
using namespace std;
// A normal function
void display() {
cout << "Displaying the shape" << endl;
}
};
int main() {
// Shape s; // Error: Cannot instantiate an abstract class
delete shape1;
delete shape2;
return 0;
}
� Output:
Drawing a Circle
Drawing a Rectangle
Displaying the shape
Displaying the shape
virtual ~BaseClass() {
// Destructor code
}
The virtual keyword ensures that the correct destructor is called for the derived class object when
deleted through a base class pointer.
#include <iostream>
using namespace std;
// Base class
class Base {
public:
Base() {
cout << "Base class constructor" << endl;
}
// Derived class
class Derived : public Base {
public:
Derived() {
cout << "Derived class constructor" << endl;
}
int main() {
// Creating a pointer to the base class and assigning it a derived class object
Base* ptr = new Derived();
return 0;
}
� Output:
kotlin
Copy code
Base class constructor
Derived class constructor
Derived class destructor
Base class destructor
11. Write C++ program to demonstrate use of unary operator (- -) overloading using member
function and unary operator overloading (++) using friend function.
ANS: #include <iostream>
using namespace std;
class Counter {
private:
int count;
public:
// Constructor to initialize count
Counter(int c = 0) : count(c) {}
int main() {
Counter c1(10); // Create a Counter object with initial value 10
return 0;
}
Output:
Initial Count: 10
After -- operation: Count: 9
After ++ operation: Count: 10
UNIT 4
1. Explain overloading the extraction (>>) and insertion (<<) operators with the help of a
program.
ANS: Overloading Extraction (>>) and Insertion (<<) Operators in C++
In C++, the extraction (>>) and insertion (<<) operators are used with input/output streams:
cin >> is used for input (extraction).
cout << is used for output (insertion).
To use these operators with user-defined classes, we need to overload them. This is typically done
using friend functions, so they can access private members of the class.
� Syntax of Overloading:
� Example Program
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNo;
float marks;
public:
// Friend function to overload extraction operator >>
friend istream& operator>>(istream& in, Student& s);
int main() {
Student s1;
return 0;
}
� Output:
Student Details:
Name: Rahul
Roll No: 101
Marks: 88.5
2. What are File Pointers? Explain seekg() and tellg() functions with syntax.
ANS: file pointers are internal pointers that keep track of the current read or write position in a file
when using file streams (like ifstream, ofstream, or fstream). They are crucial for random access to
file data.
There are two types of file pointers:
1. get pointer – Used for reading from a file (ifstream or fstream in input mode).
2. put pointer – Used for writing to a file (ofstream or fstream in output mode).
� Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("example.txt");
if (!fin) {
cout << "File not found!" << endl;
return 1;
}
char ch;
fin >> ch;
cout << "Character read: " << ch << endl;
fin.close();
return 0;
}
� Output :
3. Write a program that emulates the DOS COPY command. That is, it should copy the
contents of a text file (such as any .CPP file) to another file. Invoke the program with two
command-line arguments-the source file and the destination file-like this; C>ocopy
srcfile.cpp destfile.cpp In the program, check that the user has typed the correct number
of command-line arguments, and that the files specified can be opened.
ANS:
#include <iostream>
#include <fstream>
using namespace std;
cout << "File copied successfully from " << argv[1] << " to " << argv[2] << endl;
// Close files
srcFile.close();
destFile.close();
return 0;
}
4. Explain the errror handling in file I/O.
ANS: Error Handling in File I/O in C++
In C++, file I/O operations can fail for many reasons—such as:
File doesn't exist
Permission denied
Disk is full
End of file (EOF) reached
Read/write errors
To handle such issues, C++ provides error flags and functions associated with file stream objects
(ifstream, ofstream, fstream).
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("data.txt");
char ch;
while (file.get(ch)) {
cout << ch;
}
file.close();
return 0;
}
<contents of data.txt>
End of file reached.
5. Explain the two ways in which files can be opened, open () and Using constructor with a
program.
ANS: 1. Using Constructor
When an object of ifstream, ofstream, or fstream is created, a file can be opened by passing the
filename and mode directly to the constructor.
� Syntax:
cpp
Copy code
ifstream fin("file.txt"); // Open file for reading
ofstream fout("file.txt"); // Open file for writing
ifstream fin;
fin.open("file.txt");
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// --- Using Constructor ---
ofstream fout("example1.txt"); // Open file using constructor
if (!fout) {
cout << "Error opening file using constructor!" << endl;
return 1;
}
fout << "This file was opened using constructor.\n";
fout.close();
6. What is stream? Explain types of stream available in C++ i.e istream, ostream, ifstream and
ofstream.
ANS: a stream is an abstraction that represents a flow of data — either input (to the program) or
output (from the program). You can think of it as a sequence of characters that flows like a stream of
water.
There are two main types:
Input Stream (istream): For reading data into the program.
Output Stream (ostream): For writing data out of the program.
Streams are used with console I/O and file I/O in C++.
� Descriptions
� 1. istream (Input Stream)
Used to read input from standard input (keyboard).
Common object: cin
int x;
cin >> x; // Input from keyboard
ofstream fout("output.txt");
fout << "File output";
fout.close();
7. List and Explain different Mode bits used in open() function, while opening a file
ANS: when opening a file using the open() function (with ifstream, ofstream, or fstream), you can
specify mode bits to define how the file should be accessed — read, write, append, binary, etc.
These mode bits are defined in the <fstream> header and are passed as arguments to the open()
function.
int main() {
// Open file for writing in append mode
ofstream fout;
fout.open("example.txt", ios::out | ios::app);
if (!fout) {
cout << "Error opening file!" << endl;
return 1;
}
8. Define a class Book that has three attributes viz bookname, author and price. Write a C++
Program that writes an object to a file and reads an object from a file.
ANS: #include <iostream>
#include <fstream>
using namespace std;
class Book {
private:
char bookname[50];
char author[50];
float price;
public:
void getData() {
cout << "Enter book name: ";
cin.getline(bookname, 50);
cout << "Enter author name: ";
cin.getline(author, 50);
cout << "Enter price: ";
cin >> price;
cin.ignore(); // to clear the newline character
}
void displayData() {
cout << "Book Name : " << bookname << endl;
cout << "Author : " << author << endl;
cout << "Price : " << price << endl;
}
};
int main() {
Book b1;
return 0;
}
Output:
Enter book details:
Enter book name: C++ Primer
Enter author name: Lippman
Enter price: 599.99
9. What do you mean by File Handling? Explain following functions with syntax and an
example. i) open() ii) read() iii) write().
ANS: File handling in C++ refers to reading from and writing to files on the disk using streams
(ifstream, ofstream, fstream). It allows storing data permanently, reading it back, and modifying it as
needed.
� i) open() Function
Purpose: Opens a file in a specified mode.
Syntax:
stream_object.open("filename", mode);
Modes include:
ios::in →�input�(read)
ios::out →�output�(write)
ios::app →�append
ios::binary →�binary�mode
ios::ate →�go�to�end�of file
Example:
ofstream fout;
fout.open("data.txt", ios::out);
fout << "Hello, File!";
fout.close();
Example:
class Student {
char name[30];
int roll;
public:
void getData() {
strcpy(name, "John");
roll = 101;
}
};
int main() {
Student s;
s.getData();
ofstream fout("student.dat", ios::binary);
fout.write((char*)&s, sizeof(s));
fout.close();
return 0;
}
Example (continued):
Student s2;
ifstream fin("student.dat", ios::binary);
fin.read((char*)&s2, sizeof(s2));
fin.close();
10. Explain command line arguments in C++? Write program to explain the same.
ANS: Command Line Arguments in C++
Definition:
Command line arguments allow users to pass parameters to a program at the time of execution
from the terminal or command prompt.
Main Function Syntax with Command Line Arguments:
int main(int argc, char* argv[])
argc: (Argument Count) – Number of arguments passed, including the program name.
argv[]: (Argument Vector) – Array of character pointers listing all arguments. argv[0] is the
name of the program.
argv[1] to argv[argc-1] are the actual user-supplied arguments.
Use Case:
Reading file names
Taking user input at runtime without cin
Automating batch processing
11. Which header file do we use for file handling? Explain the following file handling functions
i) seekg ( ) ii)tellg ( ) iii)seekp ( ) iv) tellp ( )
ANS: file handling is supported by the <fstream> header file.
#include <fstream>
This provides:
ifstream →�for�input�(reading�from�files)
ofstream →�for�output�(writing�to�files)
fstream →�for�both�input�and�output
i) seekg()
Meaning: Seek Get – Moves the input (get) pointer to a specific location in the file.
Syntax:
fin.seekg(position);
fin.seekg(offset, direction);
Directions:
o ios::beg →�beginning�of�file
o ios::cur →�current�position
o ios::end →�end�of�file
Example:
fin.seekg(0, ios::end); // move to end of file
ii) tellg()
Meaning: Tell Get – Returns the current position of the get pointer.
Syntax:
streampos pos = fin.tellg();
Example:
cout << "Current read position: " << fin.tellg() << endl;
iii) seekp()
Meaning: Seek Put – Moves the output (put) pointer to a specific location.
Syntax:
fout.seekp(position);
fout.seekp(offset, direction);
Example:
fout.seekp(5, ios::beg); // move 5 bytes from beginning
iv) tellp()
Meaning: Tell Put – Returns the current position of the put pointer.
Syntax:
streampos pos = fout.tellp();
Example:
cout << "Current write position: " << fout.tellp() << endl;
UNIT 5
� Syntax:
try {
// Code that might throw an exception
} catch (exception_type1 e1) {
// Code to handle exception_type1
} catch (exception_type2 e2) {
// Code to handle exception_type2
}
try block contains the code that might throw an exception.
throw statement raises an exception when an error occurs.
catch block handles the exception and provides an alternative action.
Types of Exceptions
1. Standard Exception Types:
o std::exception: Base class for all standard exceptions.
o std::runtime_error: Used for runtime errors.
o std::invalid_argument: Raised when a function receives invalid arguments.
2. User-Defined Exceptions: Custom exceptions can be created for specific needs.
int main() {
double num1 = 10, num2 = 0;
try {
cout << "Result: " << divide(num1, num2) << endl; // this will throw exception
} catch (const DivisionByZeroException& e) {
cout << e.what() << endl; // Handle the exception
} catch (const exception& e) {
cout << "Caught a general exception: " << e.what() << endl;
}
return 0;
}
// Class template
template <typename T>
class Box {
private:
T length;
public:
Box(T len) : length(len) {}
// Getter function
T getLength() {
return length;
}
// Setter function
void setLength(T len) {
length = len;
}
int main() {
// Create an object of Box with int type
Box<int> intBox(5);
cout << "Length of intBox: " << intBox.getLength() << endl;
cout << "Volume of intBox: " << intBox.calculateVolume() << endl;
return 0;
}
int main() {
double num, denom;
try {
// Attempt division
double result = divide(num, denom);
cout << "Result: " << result << endl;
}
catch (const invalid_argument& e) {
// Catch the divide by zero exception
cout << e.what() << endl;
}
return 0;
}
2. throw:
The throw keyword is used to throw an exception when a certain error or unwanted condition is
encountered. When an exception is thrown, the normal flow of the program is interrupted, and
control is passed to the nearest catch block.
Syntax:
throw exception_object; // You can throw any type of object
You can throw objects of any type, but typically, exceptions are thrown using std::exception
or its derived classes.
Example:
if (denominator == 0) {
throw std::invalid_argument("Error: Division by zero!");
}
3. catch:
The catch block defines how to handle exceptions that are thrown. It catches the exception object
thrown by the throw statement and executes code to handle the exception. You can have multiple
catch blocks to handle different types of exceptions.
Syntax:
catch (exception_type e) {
// Handle the exception
}
Example:
try {
// Code that might throw an exception
} catch (const std::invalid_argument& e) {
std::cout << "Caught an exception: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cout << "Caught a general exception: " << e.what() << std::endl;
}
#include <iostream>
#include <stdexcept> // for std::invalid_argument
try {
double result = divide(num, denom); // Try to perform division
cout << "Result: " << result << endl;
}
catch (const std::invalid_argument& e) {
// Catch and handle division by zero
cout << "Caught exception: " << e.what() << endl;
}
return 0;
}
� Explanation of Keywords:
1. try:
o Defines a block of code that may throw an exception.
o If an exception occurs in this block, control is transferred to the nearest catch block.
2. throw:
o Used to throw an exception manually when an error or specific condition is
encountered.
o The type of exception (e.g., std::invalid_argument) is specified during the throw.
3. catch:
o Defines how to handle exceptions thrown by the try block.
o The exception object is passed as an argument to the catch block.
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 20;
cout << "Before Swap: x = " << x << ", y = " << y << endl;
swapValues(x, y); // swapping integers
cout << "After Swap: x = " << x << ", y = " << y << endl;
return 0;
}
Explanation:
1. template <typename T>:
o This line declares a template, where T is a placeholder for any data type. It tells the
compiler that this function can accept parameters of any type.
2. void swapValues(T& a, T& b):
o This function takes two parameters a and b of type T (generic type).
o The function swaps the values of a and b using a temporary variable temp.
3. In main():
o We call the swapValues function twice: once with int values and once with double
values.
o The function works for both types because the compiler automatically generates the
appropriate version of swapValues based on the type used in each call.
Output:
Before Swap: x = 10, y = 20
After Swap: x = 20, y = 10
Before Swap: m = 1.23, n = 4.56
After Swap: m = 4.56, n = 1.23
int main() {
int number;
try {
// Step 4: Call the function and catch any exceptions thrown
checkPositive(number);
}
catch (const NegativeNumberException& e) {
// Handle the user-defined exception
cout << "Caught exception: " << e.what() << endl;
}
return 0;
}
int main() {
int x = 5, y = 10, z = 15;
double m = 5.5, n = 10.5, o = 15.5;
return 0;
}
8. What do you mean by rethrowing exceptions. Write a program for the same.
ANS: Rethrowing exceptions means catching an exception and then throwing it again (i.e.,
propagating the exception further up the call stack). This is done when you want to handle the
exception partially (like logging or cleaning up resources) and then allow another part of the
program to deal with the exception more specifically.
Rethrowing is done using the throw; statement inside a catch block without specifying an exception
object.
#include <iostream>
using namespace std;
int main() {
try {
handleException();
}
catch (const std::exception& e) {
// Final handling of the exception (e.g., displaying a message)
cout << "Caught exception in main: " << e.what() << endl;
}
return 0;
}
9. What is generic programming? How it is implemented in C++.
ANS: Generic Programming is a programming paradigm that aims to write algorithms and data
structures that can work with any data type. The goal of generic programming is to design functions,
classes, and algorithms that are type-independent and can work for any data type without having to
rewrite the code for each type.
In C++, generic programming is primarily achieved using templates. Templates allow you to write
generic code that can be used with any data type, enabling reusability and flexibility.
#include <iostream>
using namespace std;
int main() {
int x = 5, y = 10;
double m = 3.14, n = 1.59;
return 0;
}
2. Class Template: A class template allows you to define a generic class that can work with any
type of data.
#include <iostream>
using namespace std;
public:
Pair(T1 f, T2 s) : first(f), second(s) {}
void display() {
cout << "First: " << first << ", Second: " << second << endl;
}
};
int main() {
Pair<int, double> p1(10, 20.5);
p1.display(); // First: 10, Second: 20.5
return 0;
}
3. Template Specialization: C++ allows the specialization of templates for specific data types,
which means you can define different implementations for specific types.
#include <iostream>
using namespace std;
// Generic function
template <typename T>
void print(T val) {
cout << "Generic: " << val << endl;
}
int main() {
print(5); // Uses the specialized version for int
print(3.14); // Uses the generic version
return 0;
}
10. Write a program in C++ to demonstrate class type exception handling in C++.
ANS: #include <iostream>
#include <exception> // For standard exception handling
using namespace std;
// Custom Exception class that inherits from std::exception
class MyException : public exception {
private:
string errorMessage;
public:
// Constructor to initialize the error message
MyException(const string& msg) : errorMessage(msg) {}
int main() {
try {
// Test cases
checkValue(-5); // This will throw an exception
checkValue(0); // This will also throw an exception
checkValue(10); // This will pass without exception
}
catch (const MyException& ex) {
// Catch the exception and display the error message
cout << "Caught exception: " << ex.what() << endl;
}
return 0;
}
UNIT 6
int main() {
// Creating a map of string (key) and int (value)
map<string, int> ageMap;
2. Enlist various containers in STL. Explain any one with the help of a program
ANS: STL provides a rich collection of container types that allow you to store and manipulate
collections of data efficiently. The main categories of containers in STL are:
1. Sequence Containers:
o vector: Dynamic array that can grow and shrink in size.
o deque: Double-ended queue, allows fast insertions/removals at both ends.
o list: Doubly-linked list, elements can be inserted or removed from both ends.
o array: Fixed-size array (since C++11).
o forward_list: Singly-linked list (since C++11).
2. Associative Containers:
o set: Stores unique elements in a sorted order.
o map: Stores key-value pairs with unique keys in sorted order.
o multiset: Stores multiple occurrences of elements in a sorted order.
o multimap: Stores key-value pairs with duplicate keys in sorted order.
3. Unordered Associative Containers:
o unordered_set: Stores unique elements with no specific order (hash table-based).
o unordered_map: Stores key-value pairs with unique keys and no specific order (hash
table-based).
o unordered_multiset: Stores multiple occurrences of elements with no specific order.
o unordered_multimap: Stores key-value pairs with duplicate keys and no specific
order.
4. Container Adapters:
o stack: Implements a LIFO (Last In First Out) data structure.
o queue: Implements a FIFO (First In First Out) data structure.
o priority_queue: A container that provides fast access to the largest or smallest
element.
#include <iostream>
#include <vector> // Include the vector header file
using namespace std;
int main() {
// Create a vector of integers
vector<int> vec;
// Display the first and last elements using front() and back()
cout << "First element: " << vec.front() << endl;
cout << "Last element: " << vec.back() << endl;
return 0;
}
4. What are the various algorithms available in STL? Explain any one with C++ program
ANS: STL provides a rich collection of algorithms that can be used with containers and iterators.
These algorithms are designed to work with various container types and allow you to manipulate
and process data easily.
Some of the most commonly used algorithms in STL are:
1. Sorting Algorithms:
o sort(): Sorts the elements in a container.
o partial_sort(): Sorts part of a container.
o stable_sort(): Sorts the elements while maintaining the order of equal elements.
2. Searching Algorithms:
o find(): Finds the first occurrence of an element.
o binary_search(): Checks if an element exists in a sorted container.
o lower_bound() / upper_bound(): Finds the first or last position of an element in a
sorted container.
3. Modifying Algorithms:
o reverse(): Reverses the order of elements in a container.
o rotate(): Rotates the elements in a container.
o shuffle(): Randomly shuffles the elements.
o fill(): Fills the entire container with a specific value.
o transform(): Applies a function to modify elements.
4. Numeric Algorithms:
o accumulate(): Computes the sum of elements in a range.
o inner_product(): Computes the inner product of two ranges.
o partial_sum(): Computes the partial sum of elements in a range.
5. Other Useful Algorithms:
o for_each(): Applies a function to every element in the container.
o count(): Counts occurrences of a specific value.
o unique(): Removes duplicate consecutive elements in a sorted container.
int main() {
// Initialize a vector with unsorted integers
vector<int> v = {40, 10, 30, 20, 50, 60, 5};
return 0;
}
11. Write a program to implement map in C++
ANS: #include <iostream>
#include <map> // Include the map header file
int main() {
// Create a map where keys are strings and values are integers
map<string, int> studentGrades;
return 0;
}
Output:
Student Grades:
Alice: 90
Bob: 80
Charlie: 85
David: 70
5. What is a container? What are various types of containers? Explain any two containers in
details.
ANS: A container is a data structure provided by the Standard Template Library (STL) that is used to
store and manage collections of objects. Containers hold objects of the same type and are used to
organize data, manage memory efficiently, and provide easy access to elements.
Containers in C++ are template classes, meaning that they are defined with a type parameter that
can be specified at compile-time.
Types of Containers in C++ STL:
The C++ STL provides several types of containers, each suited for different use cases. Containers can
be categorized into sequential containers, associative containers, and unordered associative
containers.
1. Sequential Containers: These containers store elements in a linear fashion (i.e., in a
sequence). The elements are stored in a specific order.
o vector
o deque
o list
o array
2. Associative Containers: These containers store elements in a way that allows for fast
searching based on keys. The elements are automatically sorted based on their keys.
o set
o map
o multiset
o multimap
3. Unordered Associative Containers: These containers store elements in a hash-table-based
structure for faster average-time complexity when accessing elements.
o unordered_set
o unordered_map
o unordered_multiset
o unordered_multimap
Detailed Explanation of Two Containers
1. Vector (Sequential Container)
A vector is a dynamic array that can change its size during runtime. It is similar to an array, but with
the added ability to resize automatically when needed. Elements in a vector are stored in contiguous
memory locations, making them efficient for random access.
Key Properties:
o Dynamic resizing: A vector can grow or shrink in size automatically.
o Efficient access: Elements can be accessed using indices, just like arrays.
o Memory management: Vectors are more efficient than arrays when it comes to
memory allocation and resizing.
o Insertion/Deletion: Efficient for insertions and deletions at the end of the vector, but
less efficient for other positions.
Syntax:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec; // Create a vector of integers
// Accessing elements
std::cout << "First element: " << vec[0] << std::endl;
std::cout << "Second element: " << vec.at(1) << std::endl;
return 0;
}
Output:
First element: 10
Second element: 20
Vector elements: 10 20 30
After pop_back, size: 2
2. Map (Associative Container)
A map is an associative container that stores key-value pairs. The keys are unique, and each key is
associated with a value. The elements in a map are stored in sorted order based on the key.
Key Properties:
o Sorted by keys: The elements are stored in ascending order of the key by default.
o Unique keys: Each key in a map must be unique, and a value can be retrieved based
on its associated key.
o Efficient searching: Maps provide efficient search, insertion, and deletion of key-
value pairs.
Syntax:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> studentGrades; // Map with integer keys and string values
return 0;
}
Output:
yaml
CopyEdit
Student with ID 1: Alice
Student with ID 2: Bob
All students:
ID: 1, Name: Alice
ID: 2, Name: Bob
ID: 3, Name: Charlie
Student with ID 2 is: Bob
Example:
std::map<int, std::string> age_map;
In this example, the map stores keys of type int and values of type std::string.
int main() {
// Declare a vector of integers
std::vector<int> numbers;
// Add elements to the vector using push_back
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
numbers.push_back(40);
return 0;
}
Syntax of sort()
#include <algorithm>
#include <vector>
sort(begin_iterator, end_iterator);
Example:
#include <iostream>
#include <vector>
#include <algorithm> // For sort
int main() {
// Vector of integers
std::vector<int> numbers = {10, 30, 50, 20, 40};
return 0;
}
10. What is a sequential container? List various sequential containers. Compare arrays and
vectors
ANS: a sequential container is a type of container in the Standard Template Library (STL) that stores
elements in a specific order, with each element accessible by its position in the sequence. The
elements in sequential containers are stored contiguously or in a way that maintains their ordering.
These containers allow operations like insertion, deletion, and access to elements in a specific
sequence.
Types of Sequential Containers in STL
1. vector:
o A dynamic array that allows random access to elements.
o The size of the vector can grow dynamically as elements are added.
o Elements are stored contiguously in memory.
2. deque (Double-Ended Queue):
o A sequence container that allows fast insertions and deletions at both the front and
back of the container.
o Unlike vectors, deques are not stored contiguously in memory. They are
implemented as a series of blocks that can grow in both directions.
3. list:
o A doubly linked list, where each element points to both the previous and the next
element.
o Allows efficient insertion and deletion at both ends but does not support direct
random access.
4. forward_list:
o A singly linked list, where each element points to the next element, but not to the
previous one.
o Allows efficient insertion and deletion at the front but has limited functionality
compared to list.
5. array (since C++11):
o A fixed-size array that is part of the standard library.
o It is a wrapper around a built-in array with added functionality, like size tracking and
support for range-based loops.
6. string:
o A container specifically designed to hold sequences of characters.
o It is essentially a specialized vector of characters.
11. What is iterator? Write a program in C++ to demonstrate the use iterator.
ANS: An iterator in C++ is an object that allows you to traverse through the elements of a container
(such as a vector, list, map, etc.). It is an abstraction of a pointer that enables accessing and
modifying the elements of a container. Iterators provide a unified way to access elements,
regardless of the underlying container type.
Types of Iterators
There are mainly five types of iterators in C++:
1. Input Iterator: Can be used to read the data in one direction (e.g., from the beginning to the
end).
2. Output Iterator: Can be used to write data in one direction.
3. Forward Iterator: Can be used to read or write data in one direction, but can only move
forward (like a single-pass iterator).
4. Bidirectional Iterator: Can move in both directions (forward and backward).
5. Random Access Iterator: Can move freely in both directions and allows direct access to
elements using the [] operator.
#include <iostream>
#include <vector>
int main() {
// Declare and initialize a vector
std::vector<int> numbers = {10, 20, 30, 40, 50};
return 0;
}
Output:
Elements in the vector: 10 20 30 40 50
Modified vector elements: 15 25 35 45 55