SlideShare ist ein Scribd-Unternehmen logo
1 von 29
NITK Codechef Campus Chapter

COMPETITVE PROGRAMMING LECTURE SERIES
TALK 1
TOPICS : STL & IMPLEMENTATION

By : R Anirudh
Main Building
February 8th 2014
Slide 1
STANDARD TEMPLATE LIBRARY

Why STL ?
●

Standard Template Library is poweful tool for
effecient programming.

●

It reduces length of the code and makes it clean.

●

It is well tested and optimized.

●

Advantage over your peers. If you know STL you
sort an array with a line of code while your friends
write the entire nlogn algorithm such as
mergesort for the same.

Slide 2
STANDARD TEMPLATE LIBRARY

PRE-REQUISITES TO USE STL
●
●

●

Add #include<algorithm> to use the library
Add other header files such as #include<stack> for stack
data structure. Similarly for other data-structures.
Use a good reference material . You need not remember
every function. Knowing how to use a reference material is
suuficient :)
Links for materials
1. http://www.cplusplus.com/reference
2. https://www.sgi.com/tech/stl/

Slide 3
STANDARD TEMPLATE LIBRARY

USE OF STL IN ALGORITHMS

Slide 4
STANDARD TEMPLATE LIBRARY

Terminology in STL
●

A range is any sequence of objects that can be
accessed through iterators or pointers, such as an array
or an instance of some of the STL containers.
Syntax :STL_FUNC(begin iterator,end iterator)

●

Assume an array called 'arr' with 'n' elements for the
entire lecture.
*Iterator and pointer may be used interchangbly

Slide 5
STANDARD TEMPLATE LIBRARY

SIMPLE UTILITY FUNCTIONS
●

Swapping two nos. a & b
swap(a,b)
Time complexity – constant

●

Minimum of two nos. a &b
min(a,b)
Time complexity – Constant

●

Similarly for maximum use max(a,b)

Slide 6
STANDARD TEMPLATE LIBRARY

UTILITY FUNCTIONS IN ARRAYS
●

To find the maximum value in an array of n elements
simply use
max_element(arr,arr+n)

●

Similarly for minimum use
min_element(arr,arr+n)

●

To sort an array use the function sort
sort(arr,arr+n)
Time complexity – O(nlogn) is as effecient as the
commonly used merge/heap sort.

Slide 7
STANDARD TEMPLATE LIBRARY

UTILITY FUNCTIONS IN ARRAYS
●

To reverse the the order of the elements in the range [first,last) use
reverse(arr,arr+n)
Complexity – Linear

●

To find an element in a given range use
find(arr,arr+n)
Returns an iterator to the first element in the range [first,last) that
compares equal to val. If no such element is found, the function
returns last.
Time Complexity - Linear

Slide 8
STANDARD TEMPLATE LIBRARY

OTHER USEFUL FUNCTIONS
●

●

●

●

●

binary_search(arr,arr+n,search_value) : Test if value exists in sorted
sequence
count(arr,arr+n,val) : Returns the number of elements in the range
[first,last) that compare equal to val.
lower_bound(arr,arr+n,val) : Returns an iterator pointing to the first
element in the range [first,last) which does not compare less than val
upper_bound(arr,arr+n,val) : Returns an iterator pointing to the first
element in the range [first,last) which compares greater than val.
next_permuatation(arr,arr+n) : Rearranges the elements in the range
[first,last) into the next lexicographically greater permutation.

Slide 9
STANDARD TEMPLATE LIBRARY

STL and Data-Structures

Slide 10
STANDARD TEMPLATE LIBRARY

Vector
●

●

The simplest container. It is similar to an array with additional features. Infact, the
vector library has been built using arrays.
Declare a vector
vector<int> v;

●

vector<int> v(10) means an array with 10 elements. You have allocated the
memory before hand for the vector and cannot assign any more lements.

●

Default values in a vector is 0.

●

If you wish to add elements to your declaration vector<int> v then use the function
v.push_back(val);
This adds an element at the back of the vector. This is an example of
dynamic memory allocation.

●

To get the size of a vector use the function : v.size()

Slide 11
STANDARD TEMPLATE LIBRARY

Vector
●

●

To check if a vector is empty use function v.empty() which returns true/false depending on the
content of the vector
Suppose you want to resize your vector declared as vector<int> v(10) to 15 elements use
v.resize(15) . The resize() function makes vector contain the required number of elements. If
you require less elements than vector already contain, the last ones will be deleted.

●

To clear a vector use v.clear()

●

To initialize a vector from another vector there are two ways
vector<int> v1;
vector<int> v2 = v1;
vector<int> v3(v1);
int arr[]={1,2,3};
vector<int> v(arr,arr+sizeof(arr)/sizeof(int));

Slide 12
STANDARD TEMPLATE LIBRARY

Vector
●

Creating multi-dimensional vectors. Can be done by using a vector of vectors
vector<vector<int> > matrix

●

It should now be clear how to create a 2-d vector of n*m
vector<vector<int> > matrix(n,vector<int>(m))
To initiliaze the same 2-d vector with a value
vector<vector<int> > matrix(n,vector<int>(m,55))

●

For more functions and features refer to STL guides and use google to seek
answers to your doubts. Most are available on stackoverflow.

Slide 13
STANDARD TEMPLATE LIBRARY

Pairs
●

An important data-structure resembles a structure of two-elements .
pair<int,int> pii;
How to create a pair ?
Pii = make_pair(10,15)

●

The great advantage of pairs is that they have built-in operations to
compare themselves . To access pairs use
int x = pii.first;
int y = pii.second;

●

Pairs become very important in sorting by value.

Slide 14
STANDARD TEMPLATE LIBRARY

Strings
●

STL has in-built container to manipulate strings.

●

Resembles java strings.

●

Makes string functions very simple.
If you want to concatenate two strings
string c = string a + string b

Slide 15
STANDARD TEMPLATE LIBRARY

Sets
Used when ?
●

add an element, but do not allow duplicates.

●

Remove elements

●

Get a count of distinct elements

Slide 16
STANDARD TEMPLATE LIBRARY

Sets
Implementaion
set<int> s;
for(int i = 1; i <= 100; i++) {
s.insert(i); // Insert 100 elements, [1..100]
}
s.insert(5);

// Doesn't do anything. Duplicate !!

s.erase(6); // Removes 6th element

Slide 17
STANDARD TEMPLATE LIBRARY

Maps
●

Maps contain pairs<key,value>

●

Map ensures that at most one pair with specific key exists

map<string, int> M;
M["Top"] = 1;
M["Coder"] = 2;
M["SRM"] = 10;

int x = M["Top"] + M["Coder"];

Slide 18
STANDARD TEMPLATE LIBRARY

Maps
●

Iterating through a map.
map<int,string> m;
m[1]=”Ajith”;
m[2]=”Kumar”;
map<int,string>::iterator it;
for(it=m.begin();it!=m.end();it++)
{
if(it->second==''ajith”)
cout<<”Here's our superstar”;
}

Slide 19
STANDARD TEMPLATE LIBRARY

Stacks
●

Last in , first out (LIFO)

●

Supports three constant-time operations
- push(x) : inserts x into the stack
- pop(x) : removes the newest element
- top() : returns the topmost element.

Slide 20
STANDARD TEMPLATE LIBRARY

Stacks
●

Declare #include<stack>

●

Create a stack by simply writing
stack<data_type> name_of_stack
For example : stack<int> mystack

●

To push an element
mystack.push(x);

●

To pop an element
mystack.pop();

●

To get the top of the stack
mystack.top();

●

To check if the stack is empty (crucial in case of under-flow !!! )
mystack.empty() returns true/false depending on the content of the
stack.
Slide 21
STANDARD TEMPLATE LIBRARY

Problems on Stacks
●

●

http://codeforces.com/problemset/problem/344
/D
http://www.codechef.com/problems/BEX

Slide 22
STANDARD TEMPLATE LIBRARY

Problems on Stacks
●

http://codeforces.com/problemset/problem/344
/D

●

http://www.codechef.com/problems/BEX

●

http://www.spoj.com/problems/STPAR/

Slide 23
STANDARD TEMPLATE LIBRARY

Queues
●

First in , first out (LIFO)

●

Supports three constant-time operations
- Enque(x) : inserts x into the stack
- Dequeue(x) : removes the oldest element
- front() : returns the oldest item.

Slide 24
STANDARD TEMPLATE LIBRARY

Queues
queue<int> Queue;
Queue.push(5);
Queue.push(6);

// Inserts an element into a queue

int x = Q.front();

// Returns the oldest element

Queue.pop();

// Pops the oldest element

Queue.empty(); // Returns true/false depending on content

Slide 25
STANDARD TEMPLATE LIBRARY

Importance of STL
●

●

●

Makes it very easy to implement graph algorithms like
Dijkstra's Shortest Path Algorithm by making use of
priority_queue or else we would have to implement a heap
from the scratch.
Min-heaps and max-heaps are easy to use because of the
priority_queue
Network Flow algorithms & graphs are the areas where STL
enhances quick and clean coding. We will discuss more
features and uses of STL in the upcoming lectures.

Slide 26
STANDARD TEMPLATE LIBRARY

Problems on STL
●

●

Set - http://www.spoj.com/problems/FACEFRND
Sorting based on Pair values http://www.codechef.com/problems/LEMUSIC

●

Maps extensively used - http://www.codechef.com/problems/TOURMAP

●

STL problems
1.http://www.spoj.com/problems/AMR12G/
2.http://www.spoj.com/problems/HOMO/
3.http://www.spoj.com/problems/SANTA1/

Slide 27
STANDARD TEMPLATE LIBRARY

Resources
●

Topcoder Tutorial on STL : http://community.topcoder.com/tc?
module=Static&d1=tutorials&d2=standardTemplateLibrary

●

C++ Reference – http://cplusplus.com/reference

●

Code chef – http://codechef.com

●

SPOJ – http://spoj.com

●

Code forces – http://codeforces.com

Slide 28
STANDARD TEMPLATE LIBRARY

Need more help ?
●

Try reading the topcoder tutorial thourougly + go through the STL manuals suggested.

●

Solve a good numbers of problems suggested here.

●

Do try SPOJ problems from 1-100 sorted in order of increasing order of difficulty
http://www.spoj.com/problems/classical/sort=-6

If you still have doubts/queries feel free to contact
Anirudh – anirudht20@gmail.com
Tushar – tusharmakkar08@gmail.com
Aditya kadam – adityak93@gmail.com
Ashish Kedia – ashish1294@gmail.com

Slide 29

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]
 
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Queues
QueuesQueues
Queues
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
Queues
QueuesQueues
Queues
 
Introduction to FreeMat
Introduction to FreeMatIntroduction to FreeMat
Introduction to FreeMat
 
Team 6
Team 6Team 6
Team 6
 
stack presentation
stack presentationstack presentation
stack presentation
 
Queue
QueueQueue
Queue
 
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 7) A Concise and Practical Introduction to Programming Algorithms in...
 
Queue
QueueQueue
Queue
 
Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C
 
Queue
QueueQueue
Queue
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPy
 
Queue
QueueQueue
Queue
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queue
 

Andere mochten auch

Talk on Graph Theory - I
Talk on Graph Theory - ITalk on Graph Theory - I
Talk on Graph Theory - IAnirudh Raja
 
Discrete maths assignment
Discrete maths assignmentDiscrete maths assignment
Discrete maths assignmentKeshav Somani
 
Vertex edge graphs
Vertex edge graphsVertex edge graphs
Vertex edge graphsemteacher
 
Vertex Edge Graphs
Vertex Edge GraphsVertex Edge Graphs
Vertex Edge Graphsmrwilliams
 
Graphs, Trees, Paths and Their Representations
Graphs, Trees, Paths and Their RepresentationsGraphs, Trees, Paths and Their Representations
Graphs, Trees, Paths and Their RepresentationsAmrinder Arora
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphsmaznabili
 
Solving Problems with Graphs
Solving Problems with GraphsSolving Problems with Graphs
Solving Problems with GraphsMarko Rodriguez
 
Matrix Representation Of Graph
Matrix Representation Of GraphMatrix Representation Of Graph
Matrix Representation Of GraphAbhishek Pachisia
 
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph ColouringGraph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph ColouringSaurabh Kaushik
 
The Graph Traversal Programming Pattern
The Graph Traversal Programming PatternThe Graph Traversal Programming Pattern
The Graph Traversal Programming PatternMarko Rodriguez
 
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...Marko Rodriguez
 

Andere mochten auch (16)

Talk on Graph Theory - I
Talk on Graph Theory - ITalk on Graph Theory - I
Talk on Graph Theory - I
 
Discrete maths assignment
Discrete maths assignmentDiscrete maths assignment
Discrete maths assignment
 
Graph theory1234
Graph theory1234Graph theory1234
Graph theory1234
 
Vertex edge graphs
Vertex edge graphsVertex edge graphs
Vertex edge graphs
 
Vertex Edge Graphs
Vertex Edge GraphsVertex Edge Graphs
Vertex Edge Graphs
 
Graphs, Trees, Paths and Their Representations
Graphs, Trees, Paths and Their RepresentationsGraphs, Trees, Paths and Their Representations
Graphs, Trees, Paths and Their Representations
 
Trees and graphs
Trees and graphsTrees and graphs
Trees and graphs
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
 
Solving Problems with Graphs
Solving Problems with GraphsSolving Problems with Graphs
Solving Problems with Graphs
 
Matrix Representation Of Graph
Matrix Representation Of GraphMatrix Representation Of Graph
Matrix Representation Of Graph
 
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph ColouringGraph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
 
Introduction to White box testing
Introduction to White box testingIntroduction to White box testing
Introduction to White box testing
 
The Graph Traversal Programming Pattern
The Graph Traversal Programming PatternThe Graph Traversal Programming Pattern
The Graph Traversal Programming Pattern
 
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
 
Graph theory
Graph theoryGraph theory
Graph theory
 

Ähnlich wie Talk on Standard Template Library

C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxAbhishek Tirkey
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
 
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxAssg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxfestockton
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++Khushal Mehta
 
Task and Data Parallelism: Real-World Examples
Task and Data Parallelism: Real-World ExamplesTask and Data Parallelism: Real-World Examples
Task and Data Parallelism: Real-World ExamplesSasha Goldshtein
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryGauravPatil318
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysBlue Elephant Consulting
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxdunhamadell
 
Guava Overview. Part 1 @ Bucharest JUG #1
Guava Overview. Part 1 @ Bucharest JUG #1 Guava Overview. Part 1 @ Bucharest JUG #1
Guava Overview. Part 1 @ Bucharest JUG #1 Andrei Savu
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptOliverKane3
 
basics of queues
basics of queuesbasics of queues
basics of queuessirmanohar
 
DSA-Day-2-PS.pptx
DSA-Day-2-PS.pptxDSA-Day-2-PS.pptx
DSA-Day-2-PS.pptxamanbhogal7
 

Ähnlich wie Talk on Standard Template Library (20)

C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docxAssg 14 C++ Standard Template Library (STL)(Extra Credit .docx
Assg 14 C++ Standard Template Library (STL)(Extra Credit .docx
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
 
02 stackqueue
02 stackqueue02 stackqueue
02 stackqueue
 
Task and Data Parallelism: Real-World Examples
Task and Data Parallelism: Real-World ExamplesTask and Data Parallelism: Real-World Examples
Task and Data Parallelism: Real-World Examples
 
2 b queues
2 b queues2 b queues
2 b queues
 
Task and Data Parallelism
Task and Data ParallelismTask and Data Parallelism
Task and Data Parallelism
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docx
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
Guava Overview. Part 1 @ Bucharest JUG #1
Guava Overview. Part 1 @ Bucharest JUG #1 Guava Overview. Part 1 @ Bucharest JUG #1
Guava Overview. Part 1 @ Bucharest JUG #1
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
basics of queues
basics of queuesbasics of queues
basics of queues
 
C_STL_2.pptx
C_STL_2.pptxC_STL_2.pptx
C_STL_2.pptx
 
DSA-Day-2-PS.pptx
DSA-Day-2-PS.pptxDSA-Day-2-PS.pptx
DSA-Day-2-PS.pptx
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 

Kürzlich hochgeladen

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 

Kürzlich hochgeladen (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 

Talk on Standard Template Library

  • 1. NITK Codechef Campus Chapter COMPETITVE PROGRAMMING LECTURE SERIES TALK 1 TOPICS : STL & IMPLEMENTATION By : R Anirudh Main Building February 8th 2014 Slide 1
  • 2. STANDARD TEMPLATE LIBRARY Why STL ? ● Standard Template Library is poweful tool for effecient programming. ● It reduces length of the code and makes it clean. ● It is well tested and optimized. ● Advantage over your peers. If you know STL you sort an array with a line of code while your friends write the entire nlogn algorithm such as mergesort for the same. Slide 2
  • 3. STANDARD TEMPLATE LIBRARY PRE-REQUISITES TO USE STL ● ● ● Add #include<algorithm> to use the library Add other header files such as #include<stack> for stack data structure. Similarly for other data-structures. Use a good reference material . You need not remember every function. Knowing how to use a reference material is suuficient :) Links for materials 1. http://www.cplusplus.com/reference 2. https://www.sgi.com/tech/stl/ Slide 3
  • 4. STANDARD TEMPLATE LIBRARY USE OF STL IN ALGORITHMS Slide 4
  • 5. STANDARD TEMPLATE LIBRARY Terminology in STL ● A range is any sequence of objects that can be accessed through iterators or pointers, such as an array or an instance of some of the STL containers. Syntax :STL_FUNC(begin iterator,end iterator) ● Assume an array called 'arr' with 'n' elements for the entire lecture. *Iterator and pointer may be used interchangbly Slide 5
  • 6. STANDARD TEMPLATE LIBRARY SIMPLE UTILITY FUNCTIONS ● Swapping two nos. a & b swap(a,b) Time complexity – constant ● Minimum of two nos. a &b min(a,b) Time complexity – Constant ● Similarly for maximum use max(a,b) Slide 6
  • 7. STANDARD TEMPLATE LIBRARY UTILITY FUNCTIONS IN ARRAYS ● To find the maximum value in an array of n elements simply use max_element(arr,arr+n) ● Similarly for minimum use min_element(arr,arr+n) ● To sort an array use the function sort sort(arr,arr+n) Time complexity – O(nlogn) is as effecient as the commonly used merge/heap sort. Slide 7
  • 8. STANDARD TEMPLATE LIBRARY UTILITY FUNCTIONS IN ARRAYS ● To reverse the the order of the elements in the range [first,last) use reverse(arr,arr+n) Complexity – Linear ● To find an element in a given range use find(arr,arr+n) Returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last. Time Complexity - Linear Slide 8
  • 9. STANDARD TEMPLATE LIBRARY OTHER USEFUL FUNCTIONS ● ● ● ● ● binary_search(arr,arr+n,search_value) : Test if value exists in sorted sequence count(arr,arr+n,val) : Returns the number of elements in the range [first,last) that compare equal to val. lower_bound(arr,arr+n,val) : Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val upper_bound(arr,arr+n,val) : Returns an iterator pointing to the first element in the range [first,last) which compares greater than val. next_permuatation(arr,arr+n) : Rearranges the elements in the range [first,last) into the next lexicographically greater permutation. Slide 9
  • 10. STANDARD TEMPLATE LIBRARY STL and Data-Structures Slide 10
  • 11. STANDARD TEMPLATE LIBRARY Vector ● ● The simplest container. It is similar to an array with additional features. Infact, the vector library has been built using arrays. Declare a vector vector<int> v; ● vector<int> v(10) means an array with 10 elements. You have allocated the memory before hand for the vector and cannot assign any more lements. ● Default values in a vector is 0. ● If you wish to add elements to your declaration vector<int> v then use the function v.push_back(val); This adds an element at the back of the vector. This is an example of dynamic memory allocation. ● To get the size of a vector use the function : v.size() Slide 11
  • 12. STANDARD TEMPLATE LIBRARY Vector ● ● To check if a vector is empty use function v.empty() which returns true/false depending on the content of the vector Suppose you want to resize your vector declared as vector<int> v(10) to 15 elements use v.resize(15) . The resize() function makes vector contain the required number of elements. If you require less elements than vector already contain, the last ones will be deleted. ● To clear a vector use v.clear() ● To initialize a vector from another vector there are two ways vector<int> v1; vector<int> v2 = v1; vector<int> v3(v1); int arr[]={1,2,3}; vector<int> v(arr,arr+sizeof(arr)/sizeof(int)); Slide 12
  • 13. STANDARD TEMPLATE LIBRARY Vector ● Creating multi-dimensional vectors. Can be done by using a vector of vectors vector<vector<int> > matrix ● It should now be clear how to create a 2-d vector of n*m vector<vector<int> > matrix(n,vector<int>(m)) To initiliaze the same 2-d vector with a value vector<vector<int> > matrix(n,vector<int>(m,55)) ● For more functions and features refer to STL guides and use google to seek answers to your doubts. Most are available on stackoverflow. Slide 13
  • 14. STANDARD TEMPLATE LIBRARY Pairs ● An important data-structure resembles a structure of two-elements . pair<int,int> pii; How to create a pair ? Pii = make_pair(10,15) ● The great advantage of pairs is that they have built-in operations to compare themselves . To access pairs use int x = pii.first; int y = pii.second; ● Pairs become very important in sorting by value. Slide 14
  • 15. STANDARD TEMPLATE LIBRARY Strings ● STL has in-built container to manipulate strings. ● Resembles java strings. ● Makes string functions very simple. If you want to concatenate two strings string c = string a + string b Slide 15
  • 16. STANDARD TEMPLATE LIBRARY Sets Used when ? ● add an element, but do not allow duplicates. ● Remove elements ● Get a count of distinct elements Slide 16
  • 17. STANDARD TEMPLATE LIBRARY Sets Implementaion set<int> s; for(int i = 1; i <= 100; i++) { s.insert(i); // Insert 100 elements, [1..100] } s.insert(5); // Doesn't do anything. Duplicate !! s.erase(6); // Removes 6th element Slide 17
  • 18. STANDARD TEMPLATE LIBRARY Maps ● Maps contain pairs<key,value> ● Map ensures that at most one pair with specific key exists map<string, int> M; M["Top"] = 1; M["Coder"] = 2; M["SRM"] = 10; int x = M["Top"] + M["Coder"]; Slide 18
  • 19. STANDARD TEMPLATE LIBRARY Maps ● Iterating through a map. map<int,string> m; m[1]=”Ajith”; m[2]=”Kumar”; map<int,string>::iterator it; for(it=m.begin();it!=m.end();it++) { if(it->second==''ajith”) cout<<”Here's our superstar”; } Slide 19
  • 20. STANDARD TEMPLATE LIBRARY Stacks ● Last in , first out (LIFO) ● Supports three constant-time operations - push(x) : inserts x into the stack - pop(x) : removes the newest element - top() : returns the topmost element. Slide 20
  • 21. STANDARD TEMPLATE LIBRARY Stacks ● Declare #include<stack> ● Create a stack by simply writing stack<data_type> name_of_stack For example : stack<int> mystack ● To push an element mystack.push(x); ● To pop an element mystack.pop(); ● To get the top of the stack mystack.top(); ● To check if the stack is empty (crucial in case of under-flow !!! ) mystack.empty() returns true/false depending on the content of the stack. Slide 21
  • 22. STANDARD TEMPLATE LIBRARY Problems on Stacks ● ● http://codeforces.com/problemset/problem/344 /D http://www.codechef.com/problems/BEX Slide 22
  • 23. STANDARD TEMPLATE LIBRARY Problems on Stacks ● http://codeforces.com/problemset/problem/344 /D ● http://www.codechef.com/problems/BEX ● http://www.spoj.com/problems/STPAR/ Slide 23
  • 24. STANDARD TEMPLATE LIBRARY Queues ● First in , first out (LIFO) ● Supports three constant-time operations - Enque(x) : inserts x into the stack - Dequeue(x) : removes the oldest element - front() : returns the oldest item. Slide 24
  • 25. STANDARD TEMPLATE LIBRARY Queues queue<int> Queue; Queue.push(5); Queue.push(6); // Inserts an element into a queue int x = Q.front(); // Returns the oldest element Queue.pop(); // Pops the oldest element Queue.empty(); // Returns true/false depending on content Slide 25
  • 26. STANDARD TEMPLATE LIBRARY Importance of STL ● ● ● Makes it very easy to implement graph algorithms like Dijkstra's Shortest Path Algorithm by making use of priority_queue or else we would have to implement a heap from the scratch. Min-heaps and max-heaps are easy to use because of the priority_queue Network Flow algorithms & graphs are the areas where STL enhances quick and clean coding. We will discuss more features and uses of STL in the upcoming lectures. Slide 26
  • 27. STANDARD TEMPLATE LIBRARY Problems on STL ● ● Set - http://www.spoj.com/problems/FACEFRND Sorting based on Pair values http://www.codechef.com/problems/LEMUSIC ● Maps extensively used - http://www.codechef.com/problems/TOURMAP ● STL problems 1.http://www.spoj.com/problems/AMR12G/ 2.http://www.spoj.com/problems/HOMO/ 3.http://www.spoj.com/problems/SANTA1/ Slide 27
  • 28. STANDARD TEMPLATE LIBRARY Resources ● Topcoder Tutorial on STL : http://community.topcoder.com/tc? module=Static&d1=tutorials&d2=standardTemplateLibrary ● C++ Reference – http://cplusplus.com/reference ● Code chef – http://codechef.com ● SPOJ – http://spoj.com ● Code forces – http://codeforces.com Slide 28
  • 29. STANDARD TEMPLATE LIBRARY Need more help ? ● Try reading the topcoder tutorial thourougly + go through the STL manuals suggested. ● Solve a good numbers of problems suggested here. ● Do try SPOJ problems from 1-100 sorted in order of increasing order of difficulty http://www.spoj.com/problems/classical/sort=-6 If you still have doubts/queries feel free to contact Anirudh – anirudht20@gmail.com Tushar – tusharmakkar08@gmail.com Aditya kadam – adityak93@gmail.com Ashish Kedia – ashish1294@gmail.com Slide 29