SlideShare a Scribd company logo
An Introduction To Software
Development Using C++
Class #18:
Vectors & Arrays
Problems With Your Homework #2
“No hardcoding of a solution is permitted. Your program should be able to be
run for any amount of time (e.g. two days) and produce the correct output
for the entire time.”
Thoughts On Homework #3:
A Lot Of Subroutine Calls
Return Addresses
North
South
West East
Main0
1
2
3
4
5
6
7
8
9
10
11
North
South
West
East
North
South
West
East
North
South
West
Solution? Exit
Thoughts On Homework #3:
When To End?
North
South
West East
class Stoplight
{
private:
startTime = time(0);
}
If (time(0) – startTime >= 60)
exit;
Thoughts On Homework #3:
How To Handle The Emergency Vehicle
North
South
West East
1. East is processing when
the emergency vehicle
arrives.
2. East passes control to West.
3. West commands everyone
else to go to red and it goes
to green.
4. West processes the emergency
vehicle and then resumes
normal operation.
A Common Problem
• A common problem in programming is not
knowing how many of something you have while
you’re writing a program – happens a lot.
• The Standard C++ Library has a ready-made
solution: the standard container classes. The
container classes are one of the real
powerhouses of Standard C++.
Image Credit: drvidyahattangadi.com
Say Hello To Vectors
• A vector is a collection of objects, all of which
have the same type.
• Every object in the collection has an
associated index, which gives access to that
object.
• A vector is often referred to as a container
because it “contains” other objects.
Image Credit: play.google.com
How Do We Use Vectors?
• To use a vector, we must include the
appropriate header.
#include <vector>
Image Credit: sivers.org
Introducing Vectors
• The vector class is a template, which means that it can be
efficiently applied to different types.
• That is, we can create a vector of shapes, a vector of dogs, a vector of
strings, etc.
• Basically, with a template you can create a “class of anything.”
• To tell the compiler what it is that the class will work with (in this case,
what the vector will hold), you put the name of the desired type in “angle
brackets,” which means ‘<’ and ‘>’.
• So a vector of string would be denoted vector<string>. When you do this,
you end up with a customized vector that will hold only string objects, and
you’ll get an error message from the compiler if you try to put anything
else into it.
Image Credit: http://www.viralnova.com/crazy-xray-photos/3/
All About Templates
• A vector is a class template.
• C++ has both class and function templates.
• Templates are not themselves functions or classes.
• Instead, they can be thought of as instructions to the compiler for
generating classes or functions.
• The process that the compiler uses to create classes or functions
from templates is called instantiation.
• When we use a template, we specify what kind of class or function
we want the compiler to instantiate.
Image Credit: www.digital-builder.co.uk
How To Initialize A Vector
vector<int> v1(10); // v1 has ten elements with value 0
vector<int> v2{10}; // v2 has one element with value 10
vector<int> v3(10, 1); // v3 has ten elements with value 1
vector<int> v4{10, 1}; // v4 has two elements with values 10 and 1
Image Credit: support.radioshack.com
How To Initialize A Vector
• We can usually omit the value and supply only a size.
• In this case the library creates a value-initialized element initializer for us.
This library-generated value is used to initialize each element in the
container.
• The value of the element initializer depends on the type of the elements
stored in the vector.
• If the vector holds elements of a built-in type, such as int, then the
element initializer has a value of 0. If the elements are of a class type, such
as string, then the element initializer is itself default initialized:
vector<int> ivec(10); // ten elements, each initialized to 0
vector<string> svec(10); // ten elements, each an empty string
Image Credit: www.youtube.com
Adding Things To A Vector
• Since vector expresses the concept of a “container,” there must be a way
to put things into the container and get things back out of the container.
• To add a brand-new element on the end of a vector, you use the member
function push_back( ).
• The. reason the name of this member function might seem a bit verbose
– push_back( ) instead of something simpler like “put” – is because
there are other containers and other member functions for putting
new elements into containers.
• For example, there is an insert( ) member function to put something in the
middle of a container.
• There’s also a push_front( ) (not part of vector) to put
things at the beginning.
Image Credit: blogs.courier-journal.com
How Do You Get Things
Out Of A Vector?
• So you can put new elements into a vector with push_back( ), but
how do you get these elements back out again? We make the vector look like an array.
• The array is a data type that is available in virtually every programming language so you
should already be somewhat familiar with it.
• Arrays are aggregates, which mean they consist of a number of elements clumped together.
The distinguishing characteristic of an array is that these elements are the same size and are
arranged to be one right after the other.
• Most importantly, these elements can be selected by “indexing,” which means you can say “I
want element number n” and that element will be produced, usually quickly.
• Although there are exceptions in programming languages, the indexing is normally achieved
using square brackets, so if you have an array a and you want to produce element five, you
say a[4] (note that indexing always starts at zero).
• This very compact and powerful indexing notation is incorporated into the vector.
Image Credit: www.dynafile.com
Sample Program:
Print Out File With Line Numbers// File Fillvector.cpp
// Copy an entire file into a vector of string
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
vector<string> v;
ifstream in("18 Class 01 Fillvector.cpp");
string line;
while(getline(in, line))
v.push_back(line); // Add the line to the end
// Add line numbers:
for(int i = 0; i < v.size(); i++)
cout << i << ": " << v[i] << endl;
}
0: // File Fillvector.cpp
1: // Copy an entire file into a vector of string
2:
3: #include <string>
4: #include <iostream>
5: #include <fstream>
6: #include <vector>
7:
8: #include <unistd.h>
9: #include <string.h>
10:
11: using namespace std;
12:
13: int main(){
14:
15: vector<string> v;
16:
17: ifstream in("18 Class 01 Fillvector.cpp");
18: string line;
19:
20: while(getline(in, line))
21: v.push_back(line); // Add the line to the end
22:
23: // Add line numbers:
24: for(int i = 0; i < v.size(); i++)
25: cout << i << ": " << v[i] << endl;
26:
27: }
stringobjects are pushed
onto the back of the
vector v
Once the while
loop completes,
the entire file is
resident in
memory, inside
v
1
Sample Program:
Place Integers Into A Vector
// File:Intvector.cpp
// Creating a vector that holds integers
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for(int i = 0; i < 10; i++)
v.push_back(i);
for(int i = 0; i < v.size(); i++)
cout << v[i] << ", ";
cout << endl;
for(int i = 0; i < v.size(); i++)
v[i] = v[i] * 10; // Assignment
for(int i = 0; i < v.size(); i++)
cout << v[i] << ", ";
cout << endl;
} // end of main
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 10, 20, 30, 40, 50, 60, 70, 80, 90,
You also have the ability to assign (and thus
to change) to any element of a vector, also through
the use of the square-brackets indexing operator.
2
Vector In-Class
Programming Assignment
• Create a vector<float> and put 25 floating-point numbers
into it using a for loop.
– Display the vector.
• Create three vector<float> objects and fill the first two as
in the previous exercise.
– Write a for loop that adds each corresponding element in the first two vectors
and puts the result in the corresponding element of the third vector.
– Display all three vectors.
• Create a vector<float> and put 25 numbers into it as in
the previous exercises.
– Now square each number and put the result back into the same location in
the vector.
– Display the vector before and after the multiplication.
Image Credit: blog.intellisource.com
Arrays
• An array is a consecutive group of memory locations that all have the same type.
• To refer to a particular location or element in the array, we specify the name of the array and the position number
of the particular element in the array.
• This figure shows an integer array called
c that contains 12 elements. You refer to
any one of these elements by giving the
array name followed by the particular
element’s position number in square
brackets ([]).
• The position number is more formally called a
subscript or index (this number specifies the
number of elements from the beginning of
the array).
• The first element has subscript 0 (zero) [zero indexing]
• Thus, the elements of array c are c[0]
(pronounced “c sub zero”), c[1], c[2] and so on.
• The highest subscript in array c is 11, which is 1 less than the number of elements in the array (12). Array names
follow the same conventions as other variable names.
Arrays
• A subscript must be an integer or integer expression
(using any integral type).
• If a program uses an expression as a subscript, then the program
evaluates the expression to determine the subscript.
• Example, if we assume that variable a is equal to 5 and that variable
b is equal to 6, then the statement:
adds 2 to array element c[11].
• A subscripted array name is an lvalue—it can
be used on the left side of an assignment, just
as nonarray variable names can.
c[ a + b ] += 2;
Image Credit: learningideasgradesk-8.blogspot.com
How To Declare An Array
• Arrays occupy space in memory.
• To specify the type of the elements and
the number of elements required by an
array use a declaration of the form:
type arrayName[ arraySize ];
• The compiler reserves the appropriate amount of memory. (Recall that a
declaration which reserves memory is more properly known as a
definition.)
• The arraySize must be an integer constant greater than zero. For example,
to tell the compiler to reserve 12 elements for integer array c, use the
declaration:
int c[ 12 ]; // c is an array of 12 integers
Image Credit: www.scholastic.com
How To Use An Array
• Array access is extremely fast.
• However, if you index past the
end of the array, there is no
safety net – you’ll step on
other variables.
• The other drawback is that you
must define the size of the
array at compile time; if you
want to change the size at
runtime you can’t
do it.
a[0] = 0
a[1] = 10
a[2] = 20
a[3] = 30
a[4] = 40
a[5] = 50
a[6] = 60
a[7] = 70
a[8] = 80
a[9] = 90
// File: Arrays.cpp
#include <iostream>
using namespace std;
int main() {
int a[10];
for(int i = 0; i < 10; i++) {
a[i] = i * 10;
cout << "a[" << i << "] = "
<< a[i] << endl;
}
}
In Class Programming Challenge:
Seal Team 6 & Lakeland
• You are part of a Seal team that has been ordered to
go into zombie infested Lakeland and rescue a group
of doctors at the hospital.
• Lakeland is represented by a 20 x 20 two dimensional
table that I have provided you with.
• You are to write a program that will enter the Lakeland at location (19,0) (lower left-
hand corner), work your way to the center to rescue the doctors, and then work your
way out through the exit located at (0,0). You are to avoid all contact with zombies.
Always move forward, never move behind you. Stop when you reach the extraction
point.
• A “cell” in the table that is infested with zombies contains a “1”. A clear cell has a “0”. A
cell with the doctors has an “8”.
• Every time your Seal team makes a move, print out the entire two dimensional table
and show me where you are at by marking that cell with an “-”.
What’s In Your C++ Toolbox?
cout / cin #include if/else/
Switch
Math Class String getline While
For do…While Break /
Continue
Arrays

More Related Content

What's hot

Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
Megha V
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Blue Elephant Consulting
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
BienvenidoVelezUPR
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Python programming : Threads
Python programming : ThreadsPython programming : Threads
Python programming : Threads
Emertxe Information Technologies Pvt Ltd
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
Megha V
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
Knoldus Inc.
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01Abdul Samee
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
Mahmoud Ouf
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
Scott Wlaschin
 
The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31
Mahmoud Samir Fayed
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
simarsimmygrewal
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
Knoldus Inc.
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
David Gómez García
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2Hariz Mustafa
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
Megha V
 
DotNet programming & Practices
DotNet programming & PracticesDotNet programming & Practices
DotNet programming & Practices
Dev Raj Gautam
 

What's hot (20)

Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
 
Python programming : Threads
Python programming : ThreadsPython programming : Threads
Python programming : Threads
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 
The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2
 
Algorithm analysis and design
Algorithm analysis and designAlgorithm analysis and design
Algorithm analysis and design
 
DotNet programming & Practices
DotNet programming & PracticesDotNet programming & Practices
DotNet programming & Practices
 
Function overloading
Function overloadingFunction overloading
Function overloading
 

Viewers also liked

Vectors i operacions amb vectors
Vectors i operacions amb vectorsVectors i operacions amb vectors
Vectors i operacions amb vectors
Juan Gabriel Gomila Salas
 
Lenguaje Borland C - Estructura y Componentes
Lenguaje Borland C - Estructura y ComponentesLenguaje Borland C - Estructura y Componentes
Lenguaje Borland C - Estructura y ComponentesKarina Arguedas Ruelas
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Akshay Nagpurkar
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismJussi Pohjolainen
 
Cadena caracteres
Cadena caracteresCadena caracteres
Cadena caracteres
wladimirclipper
 
Aplicación de vectores y matrices en c++
Aplicación de vectores y matrices en c++Aplicación de vectores y matrices en c++
Aplicación de vectores y matrices en c++Wladimir Pineida
 
Codigo Ascii
Codigo AsciiCodigo Ascii
Codigo Ascii
nelson
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
Dr. Md. Shohel Sayeed
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesVasavi College of Engg
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
harman kaur
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
Mohamed Loey
 
2 virtual codigo_ascii
2 virtual codigo_ascii2 virtual codigo_ascii
2 virtual codigo_asciidiazsolano
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...SlideShare
 

Viewers also liked (20)

Lista enlazada
Lista enlazadaLista enlazada
Lista enlazada
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Vectors i operacions amb vectors
Vectors i operacions amb vectorsVectors i operacions amb vectors
Vectors i operacions amb vectors
 
Lenguaje Borland C - Estructura y Componentes
Lenguaje Borland C - Estructura y ComponentesLenguaje Borland C - Estructura y Componentes
Lenguaje Borland C - Estructura y Componentes
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphism
 
Cadena caracteres
Cadena caracteresCadena caracteres
Cadena caracteres
 
Aplicación de vectores y matrices en c++
Aplicación de vectores y matrices en c++Aplicación de vectores y matrices en c++
Aplicación de vectores y matrices en c++
 
Codigo Ascii
Codigo AsciiCodigo Ascii
Codigo Ascii
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
Listas enlazadas
Listas enlazadasListas enlazadas
Listas enlazadas
 
Unit 5
Unit 5Unit 5
Unit 5
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
 
Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
C++ programming
C++ programmingC++ programming
C++ programming
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
2 virtual codigo_ascii
2 virtual codigo_ascii2 virtual codigo_ascii
2 virtual codigo_ascii
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
 

Similar to Intro To C++ - Class #18: Vectors & Arrays

Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
GauravPatil318
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
Mandeep Singh
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
SURBHI SAROHA
 
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
dunhamadell
 
Aspdot
AspdotAspdot
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
VAIBHAVKADAGANCHI
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
C++ Homework Help
 
Functions
FunctionsFunctions
Functions
PralhadKhanal1
 
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
kamalsmail1
 
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
Abhishek 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).pptx
GauravPandey43518
 
Objective c
Objective cObjective c
Objective c
ricky_chatur2005
 
cpp programing language exercise Vector.ppt
cpp programing language exercise Vector.pptcpp programing language exercise Vector.ppt
cpp programing language exercise Vector.ppt
ssuser8ac8e7
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
Akash Pandey
 
Session 4
Session 4Session 4

Similar to Intro To C++ - Class #18: Vectors & Arrays (20)

Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
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
 
Aspdot
AspdotAspdot
Aspdot
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
 
Functions
FunctionsFunctions
Functions
 
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
17-Arrays-And-Files-kkkkkkkkkkkkkkk.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
 
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
 
Objective c
Objective cObjective c
Objective c
 
cpp programing language exercise Vector.ppt
cpp programing language exercise Vector.pptcpp programing language exercise Vector.ppt
cpp programing language exercise Vector.ppt
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Session 4
Session 4Session 4
Session 4
 

Recently uploaded

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)
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
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
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
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
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
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
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
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
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 

Recently uploaded (20)

Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
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
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
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...
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
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
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 

Intro To C++ - Class #18: Vectors & Arrays

  • 1. An Introduction To Software Development Using C++ Class #18: Vectors & Arrays
  • 2. Problems With Your Homework #2 “No hardcoding of a solution is permitted. Your program should be able to be run for any amount of time (e.g. two days) and produce the correct output for the entire time.”
  • 3. Thoughts On Homework #3: A Lot Of Subroutine Calls Return Addresses North South West East Main0 1 2 3 4 5 6 7 8 9 10 11 North South West East North South West East North South West Solution? Exit
  • 4. Thoughts On Homework #3: When To End? North South West East class Stoplight { private: startTime = time(0); } If (time(0) – startTime >= 60) exit;
  • 5. Thoughts On Homework #3: How To Handle The Emergency Vehicle North South West East 1. East is processing when the emergency vehicle arrives. 2. East passes control to West. 3. West commands everyone else to go to red and it goes to green. 4. West processes the emergency vehicle and then resumes normal operation.
  • 6. A Common Problem • A common problem in programming is not knowing how many of something you have while you’re writing a program – happens a lot. • The Standard C++ Library has a ready-made solution: the standard container classes. The container classes are one of the real powerhouses of Standard C++. Image Credit: drvidyahattangadi.com
  • 7. Say Hello To Vectors • A vector is a collection of objects, all of which have the same type. • Every object in the collection has an associated index, which gives access to that object. • A vector is often referred to as a container because it “contains” other objects. Image Credit: play.google.com
  • 8. How Do We Use Vectors? • To use a vector, we must include the appropriate header. #include <vector> Image Credit: sivers.org
  • 9. Introducing Vectors • The vector class is a template, which means that it can be efficiently applied to different types. • That is, we can create a vector of shapes, a vector of dogs, a vector of strings, etc. • Basically, with a template you can create a “class of anything.” • To tell the compiler what it is that the class will work with (in this case, what the vector will hold), you put the name of the desired type in “angle brackets,” which means ‘<’ and ‘>’. • So a vector of string would be denoted vector<string>. When you do this, you end up with a customized vector that will hold only string objects, and you’ll get an error message from the compiler if you try to put anything else into it. Image Credit: http://www.viralnova.com/crazy-xray-photos/3/
  • 10. All About Templates • A vector is a class template. • C++ has both class and function templates. • Templates are not themselves functions or classes. • Instead, they can be thought of as instructions to the compiler for generating classes or functions. • The process that the compiler uses to create classes or functions from templates is called instantiation. • When we use a template, we specify what kind of class or function we want the compiler to instantiate. Image Credit: www.digital-builder.co.uk
  • 11. How To Initialize A Vector vector<int> v1(10); // v1 has ten elements with value 0 vector<int> v2{10}; // v2 has one element with value 10 vector<int> v3(10, 1); // v3 has ten elements with value 1 vector<int> v4{10, 1}; // v4 has two elements with values 10 and 1 Image Credit: support.radioshack.com
  • 12. How To Initialize A Vector • We can usually omit the value and supply only a size. • In this case the library creates a value-initialized element initializer for us. This library-generated value is used to initialize each element in the container. • The value of the element initializer depends on the type of the elements stored in the vector. • If the vector holds elements of a built-in type, such as int, then the element initializer has a value of 0. If the elements are of a class type, such as string, then the element initializer is itself default initialized: vector<int> ivec(10); // ten elements, each initialized to 0 vector<string> svec(10); // ten elements, each an empty string Image Credit: www.youtube.com
  • 13. Adding Things To A Vector • Since vector expresses the concept of a “container,” there must be a way to put things into the container and get things back out of the container. • To add a brand-new element on the end of a vector, you use the member function push_back( ). • The. reason the name of this member function might seem a bit verbose – push_back( ) instead of something simpler like “put” – is because there are other containers and other member functions for putting new elements into containers. • For example, there is an insert( ) member function to put something in the middle of a container. • There’s also a push_front( ) (not part of vector) to put things at the beginning. Image Credit: blogs.courier-journal.com
  • 14. How Do You Get Things Out Of A Vector? • So you can put new elements into a vector with push_back( ), but how do you get these elements back out again? We make the vector look like an array. • The array is a data type that is available in virtually every programming language so you should already be somewhat familiar with it. • Arrays are aggregates, which mean they consist of a number of elements clumped together. The distinguishing characteristic of an array is that these elements are the same size and are arranged to be one right after the other. • Most importantly, these elements can be selected by “indexing,” which means you can say “I want element number n” and that element will be produced, usually quickly. • Although there are exceptions in programming languages, the indexing is normally achieved using square brackets, so if you have an array a and you want to produce element five, you say a[4] (note that indexing always starts at zero). • This very compact and powerful indexing notation is incorporated into the vector. Image Credit: www.dynafile.com
  • 15. Sample Program: Print Out File With Line Numbers// File Fillvector.cpp // Copy an entire file into a vector of string #include <string> #include <iostream> #include <fstream> #include <vector> using namespace std; int main() vector<string> v; ifstream in("18 Class 01 Fillvector.cpp"); string line; while(getline(in, line)) v.push_back(line); // Add the line to the end // Add line numbers: for(int i = 0; i < v.size(); i++) cout << i << ": " << v[i] << endl; } 0: // File Fillvector.cpp 1: // Copy an entire file into a vector of string 2: 3: #include <string> 4: #include <iostream> 5: #include <fstream> 6: #include <vector> 7: 8: #include <unistd.h> 9: #include <string.h> 10: 11: using namespace std; 12: 13: int main(){ 14: 15: vector<string> v; 16: 17: ifstream in("18 Class 01 Fillvector.cpp"); 18: string line; 19: 20: while(getline(in, line)) 21: v.push_back(line); // Add the line to the end 22: 23: // Add line numbers: 24: for(int i = 0; i < v.size(); i++) 25: cout << i << ": " << v[i] << endl; 26: 27: } stringobjects are pushed onto the back of the vector v Once the while loop completes, the entire file is resident in memory, inside v 1
  • 16. Sample Program: Place Integers Into A Vector // File:Intvector.cpp // Creating a vector that holds integers #include <iostream> #include <vector> using namespace std; int main() { vector<int> v; for(int i = 0; i < 10; i++) v.push_back(i); for(int i = 0; i < v.size(); i++) cout << v[i] << ", "; cout << endl; for(int i = 0; i < v.size(); i++) v[i] = v[i] * 10; // Assignment for(int i = 0; i < v.size(); i++) cout << v[i] << ", "; cout << endl; } // end of main 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, You also have the ability to assign (and thus to change) to any element of a vector, also through the use of the square-brackets indexing operator. 2
  • 17. Vector In-Class Programming Assignment • Create a vector<float> and put 25 floating-point numbers into it using a for loop. – Display the vector. • Create three vector<float> objects and fill the first two as in the previous exercise. – Write a for loop that adds each corresponding element in the first two vectors and puts the result in the corresponding element of the third vector. – Display all three vectors. • Create a vector<float> and put 25 numbers into it as in the previous exercises. – Now square each number and put the result back into the same location in the vector. – Display the vector before and after the multiplication. Image Credit: blog.intellisource.com
  • 18. Arrays • An array is a consecutive group of memory locations that all have the same type. • To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array. • This figure shows an integer array called c that contains 12 elements. You refer to any one of these elements by giving the array name followed by the particular element’s position number in square brackets ([]). • The position number is more formally called a subscript or index (this number specifies the number of elements from the beginning of the array). • The first element has subscript 0 (zero) [zero indexing] • Thus, the elements of array c are c[0] (pronounced “c sub zero”), c[1], c[2] and so on. • The highest subscript in array c is 11, which is 1 less than the number of elements in the array (12). Array names follow the same conventions as other variable names.
  • 19. Arrays • A subscript must be an integer or integer expression (using any integral type). • If a program uses an expression as a subscript, then the program evaluates the expression to determine the subscript. • Example, if we assume that variable a is equal to 5 and that variable b is equal to 6, then the statement: adds 2 to array element c[11]. • A subscripted array name is an lvalue—it can be used on the left side of an assignment, just as nonarray variable names can. c[ a + b ] += 2; Image Credit: learningideasgradesk-8.blogspot.com
  • 20. How To Declare An Array • Arrays occupy space in memory. • To specify the type of the elements and the number of elements required by an array use a declaration of the form: type arrayName[ arraySize ]; • The compiler reserves the appropriate amount of memory. (Recall that a declaration which reserves memory is more properly known as a definition.) • The arraySize must be an integer constant greater than zero. For example, to tell the compiler to reserve 12 elements for integer array c, use the declaration: int c[ 12 ]; // c is an array of 12 integers Image Credit: www.scholastic.com
  • 21. How To Use An Array • Array access is extremely fast. • However, if you index past the end of the array, there is no safety net – you’ll step on other variables. • The other drawback is that you must define the size of the array at compile time; if you want to change the size at runtime you can’t do it. a[0] = 0 a[1] = 10 a[2] = 20 a[3] = 30 a[4] = 40 a[5] = 50 a[6] = 60 a[7] = 70 a[8] = 80 a[9] = 90 // File: Arrays.cpp #include <iostream> using namespace std; int main() { int a[10]; for(int i = 0; i < 10; i++) { a[i] = i * 10; cout << "a[" << i << "] = " << a[i] << endl; } }
  • 22. In Class Programming Challenge: Seal Team 6 & Lakeland • You are part of a Seal team that has been ordered to go into zombie infested Lakeland and rescue a group of doctors at the hospital. • Lakeland is represented by a 20 x 20 two dimensional table that I have provided you with. • You are to write a program that will enter the Lakeland at location (19,0) (lower left- hand corner), work your way to the center to rescue the doctors, and then work your way out through the exit located at (0,0). You are to avoid all contact with zombies. Always move forward, never move behind you. Stop when you reach the extraction point. • A “cell” in the table that is infested with zombies contains a “1”. A clear cell has a “0”. A cell with the doctors has an “8”. • Every time your Seal team makes a move, print out the entire two dimensional table and show me where you are at by marking that cell with an “-”.
  • 23. What’s In Your C++ Toolbox? cout / cin #include if/else/ Switch Math Class String getline While For do…While Break / Continue Arrays

Editor's Notes

  1. New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.