SlideShare a Scribd company logo
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
C++
▪ Bjarne Stroustrup (1979 - 1983, C with Classes)
▪ C++ literally means “increased C”
Structure #include <iostream>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
return 0;
}
Output int age=27;
cout<<"Output line 1"<<endl;
cout<<120<<" "<<3.1416<<" Age = "<<age<<endl;
Input int num;
double pointnum;
char ch;
cin>>num>>pointnum>>ch;
cout<<num<<" "<<pointnum<<" "<<ch<<endl;
File I/O #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
///writing to a file
ofstream myfile;
myfile.open("testfile.txt", ios::out | ios::app);
if(myfile.is_open()){
myfile<<"First line"<<endl;
myfile<<"Second line"<<endl;
myfile.close();
}
else{
cout<<"Unable to open file"<<endl;
}
///reading from a file
ifstream myfile1;
myfile1.open("testfile.txt", ios::in);
string line;
if(myfile1.is_open()){
while(!myfile1.eof()){
getline(myfile1, line);
cout<<line<<endl;
}
myfile1.close();
}
else{
cout<<"Unable to open file"<<endl;
}
return 0;
}
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
C++ : STL – Standard Template Library
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures
and functions such as dynamic arrays (vector), queues (queue), stacks (stack), associative arrays (map), etc. It is a library
of container classes, algorithms, and iterators.
STL Containers – A container is a holder of object that stores a collection of other objects. It manages the storage space
for its elements and provides member functions to access them, either directly or through iterators.
Some of the major containers:
▪ Vector
▪ Stack
▪ Queue
▪ Map
1. Vector – It represents arrays that can change in size. It uses contiguous storage locations for their elements.
Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in
order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements
to it.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
///----------------------------------------------------------------------
int arr[]={1,2,3,4};
int arrlen = sizeof(arr)/sizeof(int);
///Constructing an empty vector
vector<int> v1;
///Constructing a vector from an array
vector<int> v2 (arr, arr+arrlen);
///Constructing a vector from other vector
vector<int> v3 (v1);
///----------------------------------------------------------------------
///Accessing vector elements using iterator (points to the vector elements)
cout<<"Showing vector 2 - using Iterator"<<endl;
for(vector<int>::iterator it=v2.begin();it!=v2.end();it++){
cout<<*it<<endl;
}
///or,
cout<<"Showing vector 2 - using Index"<<endl;
for(int ind=0;ind<v2.size();ind++){
cout<<v2[ind]<<endl;
}
///To check whether the vector is empty or not
cout<<"Vector 1 empty check: "<< v1.empty() <<endl;
///----------------------------------------------------------------------
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
///Insertion - add single new element at the end of the vector, after its current last
element
v1.push_back(100);
///Insertion - insert new elements (1 or more) before the element at the specified
position
vector<int>::iterator it=v1.begin();
v1.insert(it,v2.begin(),v2.begin()+3);
cout<<"Showing vector 1 - after insertion"<<endl;
for(int ind=0;ind<v1.size();ind++){
cout<<v1[ind]<<endl;
}
///----------------------------------------------------------------------
///Deletion - remove the last element from the vector
v2.pop_back();
cout<<"Showing vector 2 - after pop_back()"<<endl;
for(int ind=0;ind<v2.size();ind++){
cout<<v2[ind]<<endl;
}
///Deletion - remove a single or range of elements from the vector
v1.erase(v1.begin()+2); ///remove only the 3rd elements
cout<<"Showing vector 1 - after erase(v1.begin()+2)"<<endl;
for(int ind=0;ind<v1.size();ind++){
cout<<v1[ind]<<endl;
}
v2.erase(v2.begin(),v2.begin()+2); ///remove the first 2 elements
cout<<"Showing vector 2 - after erase(v2.begin(), v2.begin()+2)"<<endl;
for(int ind=0;ind<v2.size();ind++){
cout<<v2[ind]<<endl;
}
///----------------------------------------------------------------------
return 0;
}
2. Stack – A type of container that operates in a LIFO (Last-in First-out) context, where elements are inserted and
extracted only from one end of the container.
#include <iostream>
#include <stack>
using namespace std;
int main()
{
///--------------------------------------------------------
///constructing an empty stack
stack<int> stk;
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
///--------------------------------------------------------
///To check the current size of the stack
cout<<"Stack size: "<< stk.size() <<endl;
///To check whether the stack is empty or not
cout<<"Stack empty check: "<< stk.empty() <<endl;
///--------------------------------------------------------
///Insertion - to push an item in the stack
cout<<"Inserting 100 and then 200"<<endl;
stk.push(100);
stk.push(200);
///--------------------------------------------------------
///Access - to access the topmost element of the stack
cout<<"Top element: "<< stk.top() <<endl;
///--------------------------------------------------------
///Deletion - to pop an item from the stack top
stk.pop();
cout<<"After pop: "<< stk.top() <<endl;
///--------------------------------------------------------
return 0;
}
3. Queue – A type of container that operates in FIFO (first-in first-out) context, where elements are inserted into one
end of the container and extracted from the other.
#include <iostream>
#include <queue>
using namespace std;
int main()
{
///------------------------------------------------------------------
///constructing an empty queue
queue<int> q;
///------------------------------------------------------------------
///To check the current size of the queue
cout<<"Size of the queue: "<<q.size()<<endl;
///To check an empty queue
cout<<"Queue empty check: "<<q.empty()<<endl;
///------------------------------------------------------------------
///Insertion - push an element at the end of the queue
cout<<"Inserting 100 and then 200"<<endl;
q.push(100);
q.push(200);
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
///------------------------------------------------------------------
///Accessing the front (oldest) element of the queue
cout<<"Oldest element: "<<q.front()<<endl;
///------------------------------------------------------------------
///Deletion - pop the oldest element from the queue
q.pop();
cout<<"After pop: "<<q.front()<<endl;
///------------------------------------------------------------------
return 0;
}
4. Map – It is an associative container that stores elements formed by a combination of a key value and a mapped
value, following a specific order. In a map, the key values are generally used to sort and uniquely identify the
elements, while the mapped values store the content associated to this key.
#include <iostream>
#include <map>
using namespace std;
int main()
{
///---------------------------------------------------------------
///constructing an empty map
map<char,int> first;
///constructing a new map from other map
map<char,int> second (first.begin(),first.end());
map<char,int> third (second);
///---------------------------------------------------------------
///Insertion - if key exists then replaces the existing value otherwise insert a new
element with that key
cout<<"Inserting a=>100 and b=>20"<<endl;
first['a']=10;
first['b']=20;
first['a']=100; ///replace
///Accessing any map element
cout<<"Accessing key a: "<< first['a']<<endl;
///---------------------------------------------------------------
///To check the size of the map
cout<<"Map size: "<<first.size()<<endl;
///To check whether the map is empty
cout<<"Map empty check: "<<first.empty()<<endl;
///---------------------------------------------------------------
///Deletion - to delete a specific map element
first.erase('b');
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
cout<<"After deletion key b, map size: "<<first.size()<<endl;
///---------------------------------------------------------------
///Search - to search for a key presence, if not found then returns map.end()
map<char,int>::iterator it=first.find('a');
if(it!=first.end()) cout<<"key a exists"<<endl;
else cout<<"key a doesn't exist"<<endl;
///---------------------------------------------------------------
///Accessing all the elements of the map
map<char,int> newmap;
newmap['a']=100;
newmap['b']=200;
newmap['c']=300;
for(map<char,int>::iterator it=newmap.begin();it!=newmap.end();it++){
cout<<"Key: "<<it->first<< " => "<<it->second<<endl;
}
///---------------------------------------------------------------
return 0;
}
#include <string> – strings are objects that represent sequence of characters.
#include <iostream>
#include <string>
using namespace std;
int main()
{
///--------------------------------------------------------
///constructing strings
string s0;
string s1 ("Initial value");
///--------------------------------------------------------
///new string assignment
s0 = "new string";
///string concatenation
string s2=s0+s1;
///to append new string at the end
s2+=" appended portion.";
///equality/greater than/less than checking
string s3 = "abc";
string s4 = "def";
cout<<"abc == def "<< (s3==s4) <<endl;
cout<<"abc != def "<< (s3!=s4) <<endl;
cout<<"abc > def "<< (s3>s4) <<endl;
cout<<"abc >= def "<< (s3>=s4) <<endl;
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
cout<<"abc < def "<< (s3<s4) <<endl;
cout<<"abc <= def "<< (s3<=s4) <<endl;
///--------------------------------------------------------
///To check the size of the string
cout<<"String length: "<<s2.size()<<endl;
///To check whether the string is empty or not
cout<<"String empty check: "<<s2.empty()<<endl;
///--------------------------------------------------------
///taking input from command prompt
string input1, input2;
getline(cin, input2); ///full line input
cin>>input1; ///word input
///outputting a string
cout<<input1<<endl;
cout<<input2<<endl;
///--------------------------------------------------------
string s5="abcdefghijghij";
///accessing specific characters
cout<<s5[2]<<endl;
///extracting substrings
cout<<s5.substr(3)<<endl; ///starting position
cout<<s5.substr(3,5)<<endl; ///starting position, length
///finding substring, returns -1 if not found
int find_index = s5.find("mno");
if(find_index==-1) cout<<"Substring not found"<<endl;
else cout<<"Substring found"<<endl;
///similarly we can use replace(), insert() and erase()
///--------------------------------------------------------
return 0;
}
#include <algorithm> – It defines a collection of functions especially designed to be used on ranges of elements (STL
containers, array etc.)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
///function for descending order sort
bool sortfn(int val1, int val2){
if(val1>val2) return true;
else return false;
}
int main()
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com
{
///------------------------------------------------------
vector<int> v;
v.push_back(100);
v.push_back(40);
v.push_back(150);
v.push_back(128);
vector<int> v1(v);
///to find out the minimum element
vector<int>::iterator minit=min_element(v.begin(), v.end());
cout<<*minit<<endl;
///to find out the maximum element
vector<int>::iterator maxit=max_element(v.begin(), v.end());
cout<<*maxit<<endl;
///To sort a vector
sort(v.begin(),v.end()); ///default: ascending order sort
cout<<"Output"<<endl;
for(int ind=0;ind<v.size();ind++){
cout<<v[ind]<<" ";
}
cout<<endl;
///To sort based on predefined rule
sort(v.begin(),v.end(),sortfn);
cout<<"Output"<<endl;
for(int ind=0;ind<v.size();ind++){
cout<<v[ind]<<" ";
}
cout<<endl;
///To reverse a vector
reverse(v1.begin(),v1.end());
cout<<"Output"<<endl;
for(int ind=0;ind<v1.size();ind++){
cout<<v1[ind]<<" ";
}
cout<<endl;
///Searching for an element
vector<int>::iterator find_ind=find(v1.begin(),v1.end(),180);
if(find_ind!=v1.end()) cout<<"Found"<<endl;
else cout<<"Not Found"<<endl;
///To count for number of occurrences
v1.push_back(99);
v1.push_back(99);
cout<<count(v1.begin(),v1.end(),99)<<endl;
return 0;
}
Reference Link: https://www.cplusplus.com/reference/

More Related Content

Similar to DS & Algo 1 - C++ and STL Introduction

Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
ajoy21
 
Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
Abdulrahman890100
 
Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
ShiraPrater50
 
Simpson and lagranje dalambair math methods
Simpson and lagranje dalambair math methods Simpson and lagranje dalambair math methods
Simpson and lagranje dalambair math methods
kinan keshkeh
 
Tugas praktikukm pemrograman c++
Tugas praktikukm  pemrograman c++Tugas praktikukm  pemrograman c++
Tugas praktikukm pemrograman c++Dendi Riadi
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
ssuser454af01
 
6Modify the bfs.java program (Listing A) to find the minimu.docx
6Modify the bfs.java program (Listing  A) to find the minimu.docx6Modify the bfs.java program (Listing  A) to find the minimu.docx
6Modify the bfs.java program (Listing A) to find the minimu.docx
evonnehoggarth79783
 
Start with the inclusion of libraries#include iostream .docx
 Start with the inclusion of libraries#include iostream .docx Start with the inclusion of libraries#include iostream .docx
Start with the inclusion of libraries#include iostream .docx
MARRY7
 
I need help with implementing the priority queue data structure with a.docx
I need help with implementing the priority queue data structure with a.docxI need help with implementing the priority queue data structure with a.docx
I need help with implementing the priority queue data structure with a.docx
hendriciraida
 
ch6_additional.ppt
ch6_additional.pptch6_additional.ppt
ch6_additional.ppt
LokeshK66
 
Ch7 C++
Ch7 C++Ch7 C++
Can you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdfCan you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdf
aksachdevahosymills
 
#include iostream #include fstream #include cstdlib #.pdf
 #include iostream #include fstream #include cstdlib #.pdf #include iostream #include fstream #include cstdlib #.pdf
#include iostream #include fstream #include cstdlib #.pdf
annesmkt
 
C++ Programs
C++ ProgramsC++ Programs
C++ Programs
NarayanlalMenariya
 
#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx
ajoy21
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdf
fsenterprises
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
kinan keshkeh
 
STACK IMPLEMENTATION USING SINGLY LINKED LIST
STACK IMPLEMENTATION USING SINGLY LINKED LISTSTACK IMPLEMENTATION USING SINGLY LINKED LIST
STACK IMPLEMENTATION USING SINGLY LINKED LIST
Er. Ganesh Ram Suwal
 

Similar to DS & Algo 1 - C++ and STL Introduction (20)

Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
 
Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
 
Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
 
Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
 
Complete the C++ program and implement the routines that are n.docx
    Complete the C++ program and implement the routines that are n.docx    Complete the C++ program and implement the routines that are n.docx
Complete the C++ program and implement the routines that are n.docx
 
Simpson and lagranje dalambair math methods
Simpson and lagranje dalambair math methods Simpson and lagranje dalambair math methods
Simpson and lagranje dalambair math methods
 
Tugas praktikukm pemrograman c++
Tugas praktikukm  pemrograman c++Tugas praktikukm  pemrograman c++
Tugas praktikukm pemrograman c++
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
 
6Modify the bfs.java program (Listing A) to find the minimu.docx
6Modify the bfs.java program (Listing  A) to find the minimu.docx6Modify the bfs.java program (Listing  A) to find the minimu.docx
6Modify the bfs.java program (Listing A) to find the minimu.docx
 
Start with the inclusion of libraries#include iostream .docx
 Start with the inclusion of libraries#include iostream .docx Start with the inclusion of libraries#include iostream .docx
Start with the inclusion of libraries#include iostream .docx
 
I need help with implementing the priority queue data structure with a.docx
I need help with implementing the priority queue data structure with a.docxI need help with implementing the priority queue data structure with a.docx
I need help with implementing the priority queue data structure with a.docx
 
ch6_additional.ppt
ch6_additional.pptch6_additional.ppt
ch6_additional.ppt
 
Ch7 C++
Ch7 C++Ch7 C++
Ch7 C++
 
Can you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdfCan you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdf
 
#include iostream #include fstream #include cstdlib #.pdf
 #include iostream #include fstream #include cstdlib #.pdf #include iostream #include fstream #include cstdlib #.pdf
#include iostream #include fstream #include cstdlib #.pdf
 
C++ Programs
C++ ProgramsC++ Programs
C++ Programs
 
#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdf
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
STACK IMPLEMENTATION USING SINGLY LINKED LIST
STACK IMPLEMENTATION USING SINGLY LINKED LISTSTACK IMPLEMENTATION USING SINGLY LINKED LIST
STACK IMPLEMENTATION USING SINGLY LINKED LIST
 

More from Mohammad Imam Hossain

DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6
Mohammad Imam Hossain
 
DS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic ProgrammingDS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic Programming
Mohammad Imam Hossain
 
DS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MSTDS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MST
Mohammad Imam Hossain
 
DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path Search
Mohammad Imam Hossain
 
DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3
Mohammad Imam Hossain
 
DS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and ConquerDS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and Conquer
Mohammad Imam Hossain
 
DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2
Mohammad Imam Hossain
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
Mohammad Imam Hossain
 
DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1
Mohammad Imam Hossain
 
DBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMSDBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMS
Mohammad Imam Hossain
 
DBMS 10 | Database Transactions
DBMS 10 | Database TransactionsDBMS 10 | Database Transactions
DBMS 10 | Database Transactions
Mohammad Imam Hossain
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational Schema
Mohammad Imam Hossain
 
DBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship ModelDBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship Model
Mohammad Imam Hossain
 
DBMS 7 | Relational Query Language
DBMS 7 | Relational Query LanguageDBMS 7 | Relational Query Language
DBMS 7 | Relational Query Language
Mohammad Imam Hossain
 
DBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML CommandsDBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML Commands
Mohammad Imam Hossain
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
Mohammad Imam Hossain
 
TOC 10 | Turing Machine
TOC 10 | Turing MachineTOC 10 | Turing Machine
TOC 10 | Turing Machine
Mohammad Imam Hossain
 
TOC 9 | Pushdown Automata
TOC 9 | Pushdown AutomataTOC 9 | Pushdown Automata
TOC 9 | Pushdown Automata
Mohammad Imam Hossain
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity Check
Mohammad Imam Hossain
 
TOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal FormTOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal Form
Mohammad Imam Hossain
 

More from Mohammad Imam Hossain (20)

DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6
 
DS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic ProgrammingDS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic Programming
 
DS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MSTDS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MST
 
DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path Search
 
DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3
 
DS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and ConquerDS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and Conquer
 
DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
 
DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1
 
DBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMSDBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMS
 
DBMS 10 | Database Transactions
DBMS 10 | Database TransactionsDBMS 10 | Database Transactions
DBMS 10 | Database Transactions
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational Schema
 
DBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship ModelDBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship Model
 
DBMS 7 | Relational Query Language
DBMS 7 | Relational Query LanguageDBMS 7 | Relational Query Language
DBMS 7 | Relational Query Language
 
DBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML CommandsDBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML Commands
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
 
TOC 10 | Turing Machine
TOC 10 | Turing MachineTOC 10 | Turing Machine
TOC 10 | Turing Machine
 
TOC 9 | Pushdown Automata
TOC 9 | Pushdown AutomataTOC 9 | Pushdown Automata
TOC 9 | Pushdown Automata
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity Check
 
TOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal FormTOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal Form
 

Recently uploaded

CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 

Recently uploaded (20)

CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 

DS & Algo 1 - C++ and STL Introduction

  • 1. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com C++ ▪ Bjarne Stroustrup (1979 - 1983, C with Classes) ▪ C++ literally means “increased C” Structure #include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; } Output int age=27; cout<<"Output line 1"<<endl; cout<<120<<" "<<3.1416<<" Age = "<<age<<endl; Input int num; double pointnum; char ch; cin>>num>>pointnum>>ch; cout<<num<<" "<<pointnum<<" "<<ch<<endl; File I/O #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ///writing to a file ofstream myfile; myfile.open("testfile.txt", ios::out | ios::app); if(myfile.is_open()){ myfile<<"First line"<<endl; myfile<<"Second line"<<endl; myfile.close(); } else{ cout<<"Unable to open file"<<endl; } ///reading from a file ifstream myfile1; myfile1.open("testfile.txt", ios::in); string line; if(myfile1.is_open()){ while(!myfile1.eof()){ getline(myfile1, line); cout<<line<<endl; } myfile1.close(); } else{ cout<<"Unable to open file"<<endl; } return 0; }
  • 2. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com C++ : STL – Standard Template Library The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as dynamic arrays (vector), queues (queue), stacks (stack), associative arrays (map), etc. It is a library of container classes, algorithms, and iterators. STL Containers – A container is a holder of object that stores a collection of other objects. It manages the storage space for its elements and provides member functions to access them, either directly or through iterators. Some of the major containers: ▪ Vector ▪ Stack ▪ Queue ▪ Map 1. Vector – It represents arrays that can change in size. It uses contiguous storage locations for their elements. Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. #include <iostream> #include <vector> using namespace std; int main() { ///---------------------------------------------------------------------- int arr[]={1,2,3,4}; int arrlen = sizeof(arr)/sizeof(int); ///Constructing an empty vector vector<int> v1; ///Constructing a vector from an array vector<int> v2 (arr, arr+arrlen); ///Constructing a vector from other vector vector<int> v3 (v1); ///---------------------------------------------------------------------- ///Accessing vector elements using iterator (points to the vector elements) cout<<"Showing vector 2 - using Iterator"<<endl; for(vector<int>::iterator it=v2.begin();it!=v2.end();it++){ cout<<*it<<endl; } ///or, cout<<"Showing vector 2 - using Index"<<endl; for(int ind=0;ind<v2.size();ind++){ cout<<v2[ind]<<endl; } ///To check whether the vector is empty or not cout<<"Vector 1 empty check: "<< v1.empty() <<endl; ///----------------------------------------------------------------------
  • 3. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com ///Insertion - add single new element at the end of the vector, after its current last element v1.push_back(100); ///Insertion - insert new elements (1 or more) before the element at the specified position vector<int>::iterator it=v1.begin(); v1.insert(it,v2.begin(),v2.begin()+3); cout<<"Showing vector 1 - after insertion"<<endl; for(int ind=0;ind<v1.size();ind++){ cout<<v1[ind]<<endl; } ///---------------------------------------------------------------------- ///Deletion - remove the last element from the vector v2.pop_back(); cout<<"Showing vector 2 - after pop_back()"<<endl; for(int ind=0;ind<v2.size();ind++){ cout<<v2[ind]<<endl; } ///Deletion - remove a single or range of elements from the vector v1.erase(v1.begin()+2); ///remove only the 3rd elements cout<<"Showing vector 1 - after erase(v1.begin()+2)"<<endl; for(int ind=0;ind<v1.size();ind++){ cout<<v1[ind]<<endl; } v2.erase(v2.begin(),v2.begin()+2); ///remove the first 2 elements cout<<"Showing vector 2 - after erase(v2.begin(), v2.begin()+2)"<<endl; for(int ind=0;ind<v2.size();ind++){ cout<<v2[ind]<<endl; } ///---------------------------------------------------------------------- return 0; } 2. Stack – A type of container that operates in a LIFO (Last-in First-out) context, where elements are inserted and extracted only from one end of the container. #include <iostream> #include <stack> using namespace std; int main() { ///-------------------------------------------------------- ///constructing an empty stack stack<int> stk;
  • 4. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com ///-------------------------------------------------------- ///To check the current size of the stack cout<<"Stack size: "<< stk.size() <<endl; ///To check whether the stack is empty or not cout<<"Stack empty check: "<< stk.empty() <<endl; ///-------------------------------------------------------- ///Insertion - to push an item in the stack cout<<"Inserting 100 and then 200"<<endl; stk.push(100); stk.push(200); ///-------------------------------------------------------- ///Access - to access the topmost element of the stack cout<<"Top element: "<< stk.top() <<endl; ///-------------------------------------------------------- ///Deletion - to pop an item from the stack top stk.pop(); cout<<"After pop: "<< stk.top() <<endl; ///-------------------------------------------------------- return 0; } 3. Queue – A type of container that operates in FIFO (first-in first-out) context, where elements are inserted into one end of the container and extracted from the other. #include <iostream> #include <queue> using namespace std; int main() { ///------------------------------------------------------------------ ///constructing an empty queue queue<int> q; ///------------------------------------------------------------------ ///To check the current size of the queue cout<<"Size of the queue: "<<q.size()<<endl; ///To check an empty queue cout<<"Queue empty check: "<<q.empty()<<endl; ///------------------------------------------------------------------ ///Insertion - push an element at the end of the queue cout<<"Inserting 100 and then 200"<<endl; q.push(100); q.push(200);
  • 5. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com ///------------------------------------------------------------------ ///Accessing the front (oldest) element of the queue cout<<"Oldest element: "<<q.front()<<endl; ///------------------------------------------------------------------ ///Deletion - pop the oldest element from the queue q.pop(); cout<<"After pop: "<<q.front()<<endl; ///------------------------------------------------------------------ return 0; } 4. Map – It is an associative container that stores elements formed by a combination of a key value and a mapped value, following a specific order. In a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key. #include <iostream> #include <map> using namespace std; int main() { ///--------------------------------------------------------------- ///constructing an empty map map<char,int> first; ///constructing a new map from other map map<char,int> second (first.begin(),first.end()); map<char,int> third (second); ///--------------------------------------------------------------- ///Insertion - if key exists then replaces the existing value otherwise insert a new element with that key cout<<"Inserting a=>100 and b=>20"<<endl; first['a']=10; first['b']=20; first['a']=100; ///replace ///Accessing any map element cout<<"Accessing key a: "<< first['a']<<endl; ///--------------------------------------------------------------- ///To check the size of the map cout<<"Map size: "<<first.size()<<endl; ///To check whether the map is empty cout<<"Map empty check: "<<first.empty()<<endl; ///--------------------------------------------------------------- ///Deletion - to delete a specific map element first.erase('b');
  • 6. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com cout<<"After deletion key b, map size: "<<first.size()<<endl; ///--------------------------------------------------------------- ///Search - to search for a key presence, if not found then returns map.end() map<char,int>::iterator it=first.find('a'); if(it!=first.end()) cout<<"key a exists"<<endl; else cout<<"key a doesn't exist"<<endl; ///--------------------------------------------------------------- ///Accessing all the elements of the map map<char,int> newmap; newmap['a']=100; newmap['b']=200; newmap['c']=300; for(map<char,int>::iterator it=newmap.begin();it!=newmap.end();it++){ cout<<"Key: "<<it->first<< " => "<<it->second<<endl; } ///--------------------------------------------------------------- return 0; } #include <string> – strings are objects that represent sequence of characters. #include <iostream> #include <string> using namespace std; int main() { ///-------------------------------------------------------- ///constructing strings string s0; string s1 ("Initial value"); ///-------------------------------------------------------- ///new string assignment s0 = "new string"; ///string concatenation string s2=s0+s1; ///to append new string at the end s2+=" appended portion."; ///equality/greater than/less than checking string s3 = "abc"; string s4 = "def"; cout<<"abc == def "<< (s3==s4) <<endl; cout<<"abc != def "<< (s3!=s4) <<endl; cout<<"abc > def "<< (s3>s4) <<endl; cout<<"abc >= def "<< (s3>=s4) <<endl;
  • 7. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com cout<<"abc < def "<< (s3<s4) <<endl; cout<<"abc <= def "<< (s3<=s4) <<endl; ///-------------------------------------------------------- ///To check the size of the string cout<<"String length: "<<s2.size()<<endl; ///To check whether the string is empty or not cout<<"String empty check: "<<s2.empty()<<endl; ///-------------------------------------------------------- ///taking input from command prompt string input1, input2; getline(cin, input2); ///full line input cin>>input1; ///word input ///outputting a string cout<<input1<<endl; cout<<input2<<endl; ///-------------------------------------------------------- string s5="abcdefghijghij"; ///accessing specific characters cout<<s5[2]<<endl; ///extracting substrings cout<<s5.substr(3)<<endl; ///starting position cout<<s5.substr(3,5)<<endl; ///starting position, length ///finding substring, returns -1 if not found int find_index = s5.find("mno"); if(find_index==-1) cout<<"Substring not found"<<endl; else cout<<"Substring found"<<endl; ///similarly we can use replace(), insert() and erase() ///-------------------------------------------------------- return 0; } #include <algorithm> – It defines a collection of functions especially designed to be used on ranges of elements (STL containers, array etc.) #include <iostream> #include <vector> #include <algorithm> using namespace std; ///function for descending order sort bool sortfn(int val1, int val2){ if(val1>val2) return true; else return false; } int main()
  • 8. Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com { ///------------------------------------------------------ vector<int> v; v.push_back(100); v.push_back(40); v.push_back(150); v.push_back(128); vector<int> v1(v); ///to find out the minimum element vector<int>::iterator minit=min_element(v.begin(), v.end()); cout<<*minit<<endl; ///to find out the maximum element vector<int>::iterator maxit=max_element(v.begin(), v.end()); cout<<*maxit<<endl; ///To sort a vector sort(v.begin(),v.end()); ///default: ascending order sort cout<<"Output"<<endl; for(int ind=0;ind<v.size();ind++){ cout<<v[ind]<<" "; } cout<<endl; ///To sort based on predefined rule sort(v.begin(),v.end(),sortfn); cout<<"Output"<<endl; for(int ind=0;ind<v.size();ind++){ cout<<v[ind]<<" "; } cout<<endl; ///To reverse a vector reverse(v1.begin(),v1.end()); cout<<"Output"<<endl; for(int ind=0;ind<v1.size();ind++){ cout<<v1[ind]<<" "; } cout<<endl; ///Searching for an element vector<int>::iterator find_ind=find(v1.begin(),v1.end(),180); if(find_ind!=v1.end()) cout<<"Found"<<endl; else cout<<"Not Found"<<endl; ///To count for number of occurrences v1.push_back(99); v1.push_back(99); cout<<count(v1.begin(),v1.end(),99)<<endl; return 0; } Reference Link: https://www.cplusplus.com/reference/