SlideShare a Scribd company logo
1 of 29
Vector ADT
Abstract Data Type (ADT)
High-level definition of data types
An ADT specifies
 A collection of data
 A set of operations on the data or subsets of the data
ADT does not specify how the operations should be
implemented
Examples
 vector, list, stack, queue, deque, priority queue, table (map),
associative array, set, graph, digraph
The Vector ADT
Generic arrays
The Vector ADT
Extends the notion of array by storing a
sequence of arbitrary objects
Elements of vector ADT can be accessed
by specifying their index.
Vectors in STL
 Collection  Elements of some proper type T
 Operations
 int size()  returns the number of elements in the vector
 void clear()  removes all elementes from the vector
 bool empty()  returns true of the vector has no elements
 void push_back ( const Object &x )
adds x to the end of the vector
 void pop_back ( )
Removes the object at the end of the vector
 Object & back ( )
Returns the object at the end of the vector
 Object & front ( )
Returns the object at the front of the vector
Vectors in STL (contd.)
More Operations
 Object & operator[] ( int index )
Returns the object at location index (without bounds checking)
Both accessor and mutator versions
 Object & at( int index )
Returns the object at location index (with bounds checking)
 int capacity()
Returns the internal capacity of the vector
 void reserve(int newCapacity)
Sets the new capacity of the vector
 void resize(int newSize )
Change the size of the vector
Implementing Vector Class Template
Vector maintains
 A primitive C++ array
 The array capacity
 The current number of items stored in the Vector
Operations:
 Copy constructor
 operator=
 Destructor to reclaim primitive array.
 All the other operators we saw earlier.
Vector Implementation (Part 1)
Constructor
Copy Constructor
deep copy assignment
Vector Implementation (Part 2)
Expand to twice as large
because memory allocation
is an expensive operation
Vector Implementation (Part 3)
No error checking
Vector Implementation (Part 4)
Same as pointers to Object
12
Standard Containers: Vectors
Adapted from Nyhoff, ADTs, Data Structures and Problem Solving with C++
13
STL (Standard Template Library)
A library of class and function templates
Components:
1. Containers:
Generic "off-the-shelf" class templates for storing
collections of data
1. Algorithms:
Generic "off-the-shelf" function templates for operating
on containers
1. Iterators:
Generalized "smart" pointers provide a generic way to
access container elements
14
Standard Template Library
Example of a specific
container class
iterator
algorithm
15
STL's 10 Containers
Kind of Container STL Containers
Sequential: deque, list,
vector
Associative: map, multimap,
multiset, set
Adapters: priority_queue,
queue, stack
16
The vector Container
A type-independent pattern for an array
class
capacity can expand
self contained
Declaration
template <typename T>
class vector
{ . . . } ;
17
The vector Container
Constructors
vector<T> v, // empty vector
v1(100), // 100 elements of type T
v2(100, val), // 100 copies of val
v3(fptr,lptr); // contains copies of
// elements in memory
// locations fptr to lptr
int intArray[5] = {9,2,7,3,12};
Int arrSize = sizeof(intArray)/sizeof(int);
vector<int> intVector(intArray, intArray+arrSize);
18
vector Operations
Information about a vector's contents
v.size()
v.empty()
v.capacity()
v.reserve(n)
Adding, removing, accessing elements
v.push_back(value)
v.pop_back()
v.front()
v.back()
19
vector Operations
Assignment
v1 = v2
Swapping
v1.swap(v2)
Relational operators
== implies element by element equality
less than < behaves like string comparison
20
Increasing Capacity of a Vector
When vector v becomes full
capacity increased automatically when item added
Algorithm to increase capacity of vector<T>
Allocate new array to store vector's elements (how
big)
use T copy constructor to copy existing elements to
new array (therefore your class must have copy constructor)
Store item being added in new array
Destroy old array in vector<T>
Make new array the vector<T>'s storage array
Expansion by addition is possible but costly
21
Increasing Capacity of a Vector
Allocate new array
Capacity doubles when more space needed
Elements copied to new array
22
Increasing Capacity of a Vector
Item being added now stored
Destroy old array
Make new array
the vector's storage
area
23
Iterators
A subscript operator is provided
BUT … this is not a generic way to access
container elements
STL provides objects called iterators
can point at an element
can access the value within that element
can move from one element to another
They are independent of any particular
container … thus a generic mechanism
24
Iterators
Given a vector which has had values
placed in the first 4 locations:
v.begin() will return the iterator value
for the first slot,
v.end() for the next empty slot
9 4 15 3
vector<int> v
v.begin()v.begin() v.end()v.end()
25
Iterators
Each STL container declares an iterator type
can be used to define iterator objects
To declare an iterator object
the identifier iterator must be preceded by
name of container
scope operator ::
Example:
vector<int>::iterator vecIter = v.begin()
26
Iterators
Basic operators that can be applied to
iterators:
increment operator ++
decrement operator --
dereferencing operator *
Assignment =
Addition, subtraction +, -, +=, -=
vecIter + n returns iterator positioned n
elements away
Subscript operator [ ]
vecIter[n] returns reference to nth
element from
current position
27
Iterators
Contrast use of subscript vs. use of iterator
ostream & operator<<(ostream & out, const
vector<double> & v)
{
for (int i = 0; i < v.size(); i++)
out << v[i] << " ";
return out;
} for (vector<double>::iterator it = v.begin();
it != v.end(); it++)
out << *it << " ";
28
Iterator Functions
Operators: ++, --, *, =. ==, !=, +, -, [ ]
Vector Functions: v.begin(), v.end(), v.rbegin(), v.rend(),
v.insert(iter, value), v.insert(iter,n,value), v.erase(iter), v.erase(iter1,iter2)
Note the capability of the last two groupings
Possible to insert, erase elements of a vector
anywhere in the vector
Must use iterators to do this
Note also these operations are as inefficient as for
arrays due to the shifting required
v.insert(iter, n, value)
v.erase(iter )
v.erase(iter1, iter2)
29
Contrast Vectors and Arrays
Vectors Arrays
• Capacity can increase
• A self contained object
• Is a class template
• Has function members
to do tasks
• Fixed size, cannot be
changed during execution
(unless using dynamic alloc)
• Cannot "operate" on
itself
•Must "re-invent the
wheel" for most actions

More Related Content

What's hot (20)

Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Arrays
ArraysArrays
Arrays
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
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
 
Array lecture
Array lectureArray lecture
Array lecture
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, Hereford
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
2D Array
2D Array 2D Array
2D Array
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
C++ Secure Programming
C++ Secure ProgrammingC++ Secure Programming
C++ Secure Programming
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
Arrays
ArraysArrays
Arrays
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
array
array array
array
 
2-D array
2-D array2-D array
2-D array
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 

Similar to Vector3

vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxvectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxVivekSharma34623
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdfadinathassociates
 
I am trying to fill out a program where the method definitions will b.docx
I am trying  to fill out a program where the method definitions will b.docxI am trying  to fill out a program where the method definitions will b.docx
I am trying to fill out a program where the method definitions will b.docxPhil4IDBrownh
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryGauravPatil318
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++Ilio Catallo
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
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
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vectornurkhaledah
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arraysAseelhalees
 

Similar to Vector3 (20)

vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxvectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
I am trying to fill out a program where the method definitions will b.docx
I am trying  to fill out a program where the method definitions will b.docxI am trying  to fill out a program where the method definitions will b.docx
I am trying to fill out a program where the method definitions will b.docx
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
STL in C++
STL in C++STL in C++
STL in C++
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
collections
collectionscollections
collections
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Statistics lab 1
Statistics lab 1Statistics lab 1
Statistics lab 1
 
Arrays
ArraysArrays
Arrays
 
Array
ArrayArray
Array
 
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
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
 

More from Rajendran

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower boundsRajendran
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsRajendran
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower boundsRajendran
 
Red black tree
Red black treeRed black tree
Red black treeRajendran
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statisticsRajendran
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theoremRajendran
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree methodRajendran
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theoremRajendran
 
Master method
Master method Master method
Master method Rajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithmsRajendran
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisRajendran
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisRajendran
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of QuicksortRajendran
 
Np completeness
Np completenessNp completeness
Np completenessRajendran
 
computer languages
computer languagescomputer languages
computer languagesRajendran
 

More from Rajendran (20)

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower bounds
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding Costs
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
 
Red black tree
Red black treeRed black tree
Red black tree
 
Hash table
Hash tableHash table
Hash table
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theorem
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
 
Master method
Master method Master method
Master method
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Hash tables
Hash tablesHash tables
Hash tables
 
Lower bound
Lower boundLower bound
Lower bound
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm Analysis
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of Quicksort
 
Np completeness
Np completenessNp completeness
Np completeness
 
computer languages
computer languagescomputer languages
computer languages
 

Recently uploaded

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
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
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 

Recently uploaded (20)

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
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
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

Vector3

  • 2. Abstract Data Type (ADT) High-level definition of data types An ADT specifies  A collection of data  A set of operations on the data or subsets of the data ADT does not specify how the operations should be implemented Examples  vector, list, stack, queue, deque, priority queue, table (map), associative array, set, graph, digraph
  • 4. The Vector ADT Extends the notion of array by storing a sequence of arbitrary objects Elements of vector ADT can be accessed by specifying their index.
  • 5. Vectors in STL  Collection  Elements of some proper type T  Operations  int size()  returns the number of elements in the vector  void clear()  removes all elementes from the vector  bool empty()  returns true of the vector has no elements  void push_back ( const Object &x ) adds x to the end of the vector  void pop_back ( ) Removes the object at the end of the vector  Object & back ( ) Returns the object at the end of the vector  Object & front ( ) Returns the object at the front of the vector
  • 6. Vectors in STL (contd.) More Operations  Object & operator[] ( int index ) Returns the object at location index (without bounds checking) Both accessor and mutator versions  Object & at( int index ) Returns the object at location index (with bounds checking)  int capacity() Returns the internal capacity of the vector  void reserve(int newCapacity) Sets the new capacity of the vector  void resize(int newSize ) Change the size of the vector
  • 7. Implementing Vector Class Template Vector maintains  A primitive C++ array  The array capacity  The current number of items stored in the Vector Operations:  Copy constructor  operator=  Destructor to reclaim primitive array.  All the other operators we saw earlier.
  • 8. Vector Implementation (Part 1) Constructor Copy Constructor deep copy assignment
  • 9. Vector Implementation (Part 2) Expand to twice as large because memory allocation is an expensive operation
  • 10. Vector Implementation (Part 3) No error checking
  • 11. Vector Implementation (Part 4) Same as pointers to Object
  • 12. 12 Standard Containers: Vectors Adapted from Nyhoff, ADTs, Data Structures and Problem Solving with C++
  • 13. 13 STL (Standard Template Library) A library of class and function templates Components: 1. Containers: Generic "off-the-shelf" class templates for storing collections of data 1. Algorithms: Generic "off-the-shelf" function templates for operating on containers 1. Iterators: Generalized "smart" pointers provide a generic way to access container elements
  • 14. 14 Standard Template Library Example of a specific container class iterator algorithm
  • 15. 15 STL's 10 Containers Kind of Container STL Containers Sequential: deque, list, vector Associative: map, multimap, multiset, set Adapters: priority_queue, queue, stack
  • 16. 16 The vector Container A type-independent pattern for an array class capacity can expand self contained Declaration template <typename T> class vector { . . . } ;
  • 17. 17 The vector Container Constructors vector<T> v, // empty vector v1(100), // 100 elements of type T v2(100, val), // 100 copies of val v3(fptr,lptr); // contains copies of // elements in memory // locations fptr to lptr int intArray[5] = {9,2,7,3,12}; Int arrSize = sizeof(intArray)/sizeof(int); vector<int> intVector(intArray, intArray+arrSize);
  • 18. 18 vector Operations Information about a vector's contents v.size() v.empty() v.capacity() v.reserve(n) Adding, removing, accessing elements v.push_back(value) v.pop_back() v.front() v.back()
  • 19. 19 vector Operations Assignment v1 = v2 Swapping v1.swap(v2) Relational operators == implies element by element equality less than < behaves like string comparison
  • 20. 20 Increasing Capacity of a Vector When vector v becomes full capacity increased automatically when item added Algorithm to increase capacity of vector<T> Allocate new array to store vector's elements (how big) use T copy constructor to copy existing elements to new array (therefore your class must have copy constructor) Store item being added in new array Destroy old array in vector<T> Make new array the vector<T>'s storage array Expansion by addition is possible but costly
  • 21. 21 Increasing Capacity of a Vector Allocate new array Capacity doubles when more space needed Elements copied to new array
  • 22. 22 Increasing Capacity of a Vector Item being added now stored Destroy old array Make new array the vector's storage area
  • 23. 23 Iterators A subscript operator is provided BUT … this is not a generic way to access container elements STL provides objects called iterators can point at an element can access the value within that element can move from one element to another They are independent of any particular container … thus a generic mechanism
  • 24. 24 Iterators Given a vector which has had values placed in the first 4 locations: v.begin() will return the iterator value for the first slot, v.end() for the next empty slot 9 4 15 3 vector<int> v v.begin()v.begin() v.end()v.end()
  • 25. 25 Iterators Each STL container declares an iterator type can be used to define iterator objects To declare an iterator object the identifier iterator must be preceded by name of container scope operator :: Example: vector<int>::iterator vecIter = v.begin()
  • 26. 26 Iterators Basic operators that can be applied to iterators: increment operator ++ decrement operator -- dereferencing operator * Assignment = Addition, subtraction +, -, +=, -= vecIter + n returns iterator positioned n elements away Subscript operator [ ] vecIter[n] returns reference to nth element from current position
  • 27. 27 Iterators Contrast use of subscript vs. use of iterator ostream & operator<<(ostream & out, const vector<double> & v) { for (int i = 0; i < v.size(); i++) out << v[i] << " "; return out; } for (vector<double>::iterator it = v.begin(); it != v.end(); it++) out << *it << " ";
  • 28. 28 Iterator Functions Operators: ++, --, *, =. ==, !=, +, -, [ ] Vector Functions: v.begin(), v.end(), v.rbegin(), v.rend(), v.insert(iter, value), v.insert(iter,n,value), v.erase(iter), v.erase(iter1,iter2) Note the capability of the last two groupings Possible to insert, erase elements of a vector anywhere in the vector Must use iterators to do this Note also these operations are as inefficient as for arrays due to the shifting required v.insert(iter, n, value) v.erase(iter ) v.erase(iter1, iter2)
  • 29. 29 Contrast Vectors and Arrays Vectors Arrays • Capacity can increase • A self contained object • Is a class template • Has function members to do tasks • Fixed size, cannot be changed during execution (unless using dynamic alloc) • Cannot "operate" on itself •Must "re-invent the wheel" for most actions

Editor's Notes

  1. Introduction Welcome to COP 4530, Data Structures, Algorithms, and Generic Programming. I hope very much, and sincerely believe, that this course will change you in ways that are deeply satisfying. So far, you have acquired proficiency in programming. This course will start the process of your transformation from a programmer to a computer scientist. One of the important tasks of a computer scientist is to make efficient use of computational resources. This course will teach you about different ways of organizing the data to facilitate such efficient use, and will also discuss efficient techniques to perform some fundamental operations in computer science. A subsequent course on Algorithms, COP 4531, will teach you to use the techniques discussed in this course to solve commonly encountered computer science problems efficiently. Both these courses will also teach you to analyze the efficiency, and prove the correctness, of your program in a mathematically rigorous manner. Material you learn in these two courses is critical to your becoming a good software developer later.
  2. Stopped 2/24/2006
  3. Algorithm must be able to operator on any container – therefore the containers provide iterators for the algorithms to use. (iterators – interface that is needed by STL algorithms to operate on STL containers)
  4. Container Adapters – adapt STL containers to fit special needs.
  5. Vector&amp;lt;double&amp;gt;dubvector(a,a+4); where a is an array….
  6. See p. 478 Capacity – return the no of places vector has Reserve – grow the vector to N
  7. What happens when the vector must grow…