0% found this document useful (0 votes)
4 views79 pages

Lecture 24

The document covers key concepts in C++ programming, focusing on classes, dynamic memory management, and the C++ Standard Template Library. It explains the differences between structs and classes, the use of input/output classes for file handling, and the importance of managing heap memory to avoid errors such as dangling references and memory leaks. Additionally, it introduces the design of a custom string class to handle memory management seamlessly.

Uploaded by

Divy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views79 pages

Lecture 24

The document covers key concepts in C++ programming, focusing on classes, dynamic memory management, and the C++ Standard Template Library. It explains the differences between structs and classes, the use of input/output classes for file handling, and the importance of managing heap memory to avoid errors such as dangling references and memory leaks. Additionally, it introduces the design of a custom string class to handle memory management seamlessly.

Uploaded by

Divy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

CS 101:

Computer Programming and


Utilization

Puru
with
CS101 TAs and Staff

Course webpage: https://www.cse.iitb.ac.in/~cs101/

Lecture 24: Dynamic memory management


and the C++ Standard Template Library
CS101 Autumn 2019 @ CSE IIT Bombay
Classes
• A class is essentially the same as a struct, except:
– Any members/member functions in a struct are public by
default
– Any members/member functions in a class are private by
default

CS101 Autumn 2019 @ CSE IIT Bombay 2


Classes
• Example: A Queue class

class Queue{
int elements[N], nWaiting, front;
public:
Queue(){…}
bool remove(int &v){…}
bool insert(int v){…}
};

• The members - elements, nWaiting and front will be private.

CS101 Autumn 2019 @ CSE IIT Bombay 3


Function definition and declaration (with class)
class V3{ class V3{
double x,y,z; double x,y,z;
V3(double v){ V3(double v);
x = y = z = v; double X();
} };
double X(){
return x; //implementations
} V3::V3(double v){
}; x = y = z = v;
}
double V3::X(){
return x;
}

CS101 Autumn 2019 @ CSE IIT Bombay 4


Example (with struct)
struct V3{ struct V3{
double x,y,z; double x,y,z;
V3(double v){ V3(double v);
x = y = z = v; double X();
} };
double X(){
return x; //implementations
} V3::V3(double v){
}; x = y = z = v;
}
double V3::X(){
return x;
}

CS101 Autumn 2019 @ CSE IIT Bombay 5


The C++ Standard (Template) Library

Chapter 22

CS101 Autumn 2019 @ CSE IIT Bombay 6


The C++ Standard Library
• Comes with every C++ distribution
• Contains many functions and classes that you are likely to need in
day to day programming
• The classes have been optimized and debugged thoroughly
• If you use them, you may be able to write programs with very little
work
• Highly recommended that you use functions and classes form the
standard library whenever possible

• Files, Strings, Maps, Vectors, Sets, Lists,


Queues …

CS101 Autumn 2019 @ CSE IIT Bombay 7


Input Output Classes (stdin/stdout/files)

• cin, cout : objects of class istream, ostream resp. predefined in C++

• <<, >> : operators defined for the objects of these classes

• ifstream: another class like istream

• You create an object of class ifstream and associate it with a file on


your computer

• Now you can read from that file by invoking the >> operator!

• ofstream: a class like ostream, to be used for writing to files

• Must include header file <fstream> to uses ifstream and ofstream

CS101 Autumn 2019 @ CSE IIT Bombay 8


Example of File i/o
#include <fstream>
#include <simplecpp>
int main(){
ifstream infile(“f1.txt”);
// constructor call.
// object infile is created and associated
// with f1.txt, which must be present in the current directory

ofstream outfile(“f2.txt”);
// constructor call. Object outfile is created and associated
// with f2.txt, which will get created in the current directory

repeat(10){
int v;
infile >> v;
outfile << v;
}
// f1.txt must begin with 10 numbers. These will be read and
// written to file f2.txt
}

CS101 Autumn 2019 @ CSE IIT Bombay 9


ifstream /ofstream member functions
• open, close, is_open

• >> , <<, !

• get, getline, peek, read

• put, write

CS101 Autumn 2019 @ CSE IIT Bombay 10


“String theory”
• Iterative computations are demonstrated well on arrays

• strings … the system manages the array space for us

• string message; // a character string

• Can assign and append to strings


• Can read a position: cout << message[px]
• Can write a position: message[px] = ‘q’

CS101 Autumn 2019 @ CSE IIT Bombay 11


Strings without string
• character arrays!
char str[5] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’} ;

• why string then?

• the dreaded NULL character


• null character => character with ASCII value 0
• require null-terminated character array to represent end
of string
• no end of string can lead to chaos!

CS101 Autumn 2019 @ CSE IIT Bombay 12


Challenge with char arrays!
char str[6] = {‘e’, ‘a’, ‘r’, ‘t’, ‘h’} ;

cout << str; // early takeoff of space shuttle

str[5] = ‘\0’;
cout << str; // back to earth!

• Have to ensure null-termination at all points

• Character array sizing has to be managed (via copies


etc.) explicitly

• Not objects!
CS101 Autumn 2019 @ CSE IIT Bombay 13
the string class
string str = “earth”;

cout << str; // stay on earth!

• can use indexing as in arrays


• other member functions
– size, clear, empty,
– + , = , +=, >>, <<
– push_back, pop_back, append
– insert, erase, find, substr

CS101 Autumn 2019 @ CSE IIT Bombay 14


Printing a string in reverse
string message;
getline(cin, message);
int mx = message.size()-1;
while (mx >= 0) { Character at
cout << message[mx]; position mx in
--mx; string message
}

• mx updated in a predictable way


• Ideal candidate to write as for loop

CS101 Autumn 2019 @ CSE IIT Bombay 15


Finding needles in a haystack
• Given two strings, needles and haystack
• needles has no repeated characters
• haystack may repeat characters
• How many characters in needles appear in haystack at
least once?
• needles = “bat”, haystack = “tabla” à 3
• needles = “tab”, haystack = “bottle” à 2

CS101 Autumn 2019 @ CSE IIT Bombay 16


One needle in a haystack
• Subproblem: given one character ch and a string
find if ch appears in string at least once
char ch;
cin >> ch;
string haystack;
cin >> haystack;

int ans = 0; // will change to 1 if found


for (int hx = 0; hx < haystack.size(); ++hx) {
if (ch == haystack[hx]) {
++ans;
break; // quit on first match
}
}
CS101 Autumn 2019 @ CSE IIT Bombay 17
Many needles: nested loop
main() {
string needles, haystack;
getline(cin, needles); getline(cin, haystack);

int ans = 0;
for (int nx=0; nx < needles.size(); ++nx) {
char ch = needles[nx];
for (int hx = 0; hx < haystack.size(); ++hx) {
if (ch == haystack[hx]) {
++ans;
break; // quit on first match
}
} // ends haystack loop Generalize to work in
} // ends needles loop case needles can also
}
have repeated
characters
CS101 Autumn 2019 @ CSE IIT Bombay 18
Duplicate needles

• needles = “bat”, haystack = “tabla” à 3


• needles = “tab”, haystack = “bottle” à 2
• needles = “bata”, haystack = “tabla” à 3

• Two approaches
– Dedup needles before executing earlier code (reducing
to known problem)
– Dedup needles “on the fly” (inside the nx loop)

CS101 Autumn 2019 @ CSE IIT Bombay 19


Strings and member functions (example)
#include <string>
string v = “abcdab”;
string w(v);

v[2] = v[3]; // indexing allowed. v becomes “abddab”

cout << v.substr(2) << v.substr(1,3) << endl;


// substring starting at v[2] (“ddab”)
// substring starting at v[1] of length 3 (“bdd”)

int i = v.find(“ab”); // find occurrence of “ab” in v


// and return index
int j = v.find(“ab”,1); // find from index 1

cout << i << “, “ << j << endl; // will print out 0, 4.

CS101 Autumn 2019 @ CSE IIT Bombay 20


Dynamic memory
management

CS101 Autumn 2019 @ CSE IIT Bombay


The Heap memory
• In C++ there is a separate, reserved region of memory
called the Heap memory, or just the Heap.
• It is possible to explicitly request that memory for a
certain variable be allocated in the heap.

• When there is no more use for the variable thus


allocated, the program must explicitly return the
memory to the heap.
After the memory is returned, it can be used to satisfy
other memory allocation requests in the future.
• How?

CS101 Autumn 2019 @ CSE IIT Bombay 22


A variable on the heap to store a Book object
class Book{ • new asks for heap memory
char title[100]; • Must be followed by type
name T
double price;
}; • Memory for storing one
variable of type T is allocated
… on the heap.
• new T returns address of
Book *bptr; allocated memory.
• Now use the memory!
bptr = new Book();
bptr->price = 399; • After the memory is no longer
needed, it must be returned
by executing delete.
… • new and delete are reserved
delete bptr; words, also operators

CS101 Autumn 2019 @ CSE IIT Bombay 23


With facility comes RESPONSIBILITY!
• Allocation and deallocation is simple and convenient

• However, experience shows that managing heap memory


is tricky and prone to errors!
– forgetting to deallocate (delete) memory.
– Referring to memory that has been deallocated.
(“Dangling reference”)
– Destroying the only pointer to memory allocated on the heap
before it is deallocated (“Memory Leak”)

CS101 Autumn 2019 @ CSE IIT Bombay 24


Error 1: Dangling reference
int* iptr;
iptr = new int;
*iptr = …;
delete iptr;
*iptr = ...; // dangling reference!

• In the last statement, iptr points to memory that has been


returned, and so should not be used.
• ... it might in general be allocated for some other request.
• Here the error is obvious, but if there are many intervening
statements it may not be.

CS101 Autumn 2019 @ CSE IIT Bombay 25


Error 2: Memory Leak 1
int *iptr;
iptr = new int; // statement 1
iptr = new int; // statement 2

• Memory is allocated in statement 1, and its address, say A, is


stored in iptr.
However, this address is overwritten in statement 2.
• Memory allocated at address A cannot be used by the program
because we have destroyed the address.
• However, we did not return (delete) that memory before
destroying the address. Heap allocation functions think that it has
been given to us.
• The memory at address A has become useless! “Leaked”

CS101 Autumn 2019 @ CSE IIT Bombay 26


Error 3: Memory Leak 2
{int *iptr;
iptr = new int; // statement 1
}

Memory is allocated in statement 1, and its address, say A, is stored in


iptr.
When control exits the block, then iptr is destroyed.

Memory allocated in statement 1 cannot be used by the program because


we do not know the address any longer.

However, we did not return (delete) that memory before destroying the
address. Heap allocation functions think that it has been given to us.

Memory at address A has become unusable!

CS101 Autumn 2019 @ CSE IIT Bombay 27


Simple strategy for preventing memory leaks
• Suppose a certain pointer variable, ptr, is the only
variable that contains the address of a variable allocated
on the heap.
• We must not store anything into ptr and destroy its
contents.

• When ptr is about to go out of scope, (control exits the


block in which ptr is defined) we must execute
delete ptr;

CS101 Autumn 2019 @ CSE IIT Bombay 28


Strategy for preventing dangling references
• Why we get a dangling reference:
• There are two pointers, say aptr and bptr which point
to the same variable on the heap.
• We execute delete aptr;
• Later we dereference bptr, not realizing the memory it
points to has been deallocated.
• Simple way to avoid this:
• Ensure that at all times, each variable on the heap will be
pointed to only by one pointer!
• More complex strategies are possible. See the book.

CS101 Autumn 2019 @ CSE IIT Bombay 29


Avoiding dangling references and memory leaks

• Ensure each variable allocated on the heap is pointed


to by exactly one pointer at any time.
• If aptr points to a heap variable, then before
executing aptr = … execute delete aptr;

• If aptr points to a heap variable, and if control is


about to exit the block in which aptr is defined, then
execute delete aptr;
• We can automate this!

CS101 Autumn 2019 @ CSE IIT Bombay 30


A class for representing character strings
• We would like to build a mystring class in which
we can store character strings of arbitrary length,
without worrying about allocating memory,
memory leaks, dangling references.

• We should be able to create mystrings, pass them


to functions, concatenate them, search them, and
so on.

CS101 Autumn 2019 @ CSE IIT Bombay 31


A program we should be able to write
int main(){
• Our class should enable us to
mystring a, b, c; write the program shown.
a = “pqr”;
b = a; • Creation of string variables
{ • Assignment
mystring c = a + b; • Concatenation
// concatenation • Printing
c.print(); • Declaring arrays
}
cout << c[2] << endl; • All this requires memory
mystring d[2]; management, but that should
happen behind the scenes,
d[0] = “xyz”;
without memory leaks, dangling
d[1] = d[0] + c; pointers.
d[1].print();
}
CS101 Autumn 2019 @ CSE IIT Bombay 32
Basic ideas in designing mystring
• Store the string itself on the heap, while maintain a pointer ptr
to it inside the class.
• The string will be terminated using the null character ‘\0’.
• When no string is stored,n.set ptr to NULL.

• NULL (=0) : standard convention, means pointer is invalid.


• NULL pointer different from NULL character.
• To avoid dangling references and memory leaks, ensure that
– Each ptr will point to a distinct char array on the heap.
– Before storing anything into ptr, delete the variable it points to.
– When any ptr is about to go out of scope, delete it.

• Other designs also possible – later.

CS101 Autumn 2019 @ CSE IIT Bombay 33


mystring class!
class mystring{
char* ptr;
mystring(){ // constructor
ptr = NULL; // initially empty string
}
void print(){ // print function
if(ptr != NULL)
cout << ptr;
else
cout <<“NULL”;
}
// other member functions..
};
CS101 Autumn 2019 @ CSE IIT Bombay 34
Assigning a character string constant
• Allow a character string constant to be stored in a myString
mystring a;
a = “pqr”;
• Thus, we must define member function operator=

• Character string constant is represented by a const char*


which points to the first character in the string

• So we will define a member function operator= taking a


const char* as an argument

CS101 Autumn 2019 @ CSE IIT Bombay 35


What should happen for a = “pqr”;
• a.ptr must be set to point to a string on the heap
holding “pqr”

• Why not set a.ptr to point to “pqr” directly?


– Member ptr must point to the heap memory. The
character string constant “pqr” may not be on the heap.
• a.ptr may already be pointing to some variable on
the heap.
– We are guaranteed that no other pointer points to that
variable, so we must delete a.ptr so that the memory
occupied by the variable is returned to the heap.

CS101 Autumn 2019 @ CSE IIT Bombay 36


The code
mystring& operator=(const char* rhs){
// release the memory that ptr already points to.
delete ptr; int len(char* ptr){
int l = 0;
while(ptr[l]!='\0') l++;
// make a copy of rhs on the heap return l++;
}
// allocate len(rhs) + 1 byte to store ‘\0’
ptr = new char[len(rhs)+1];

// actually copy. Function scopy defined in book


scopy(ptr, rhs);

void scopy(char*
// We return a reference to the class to ptr, char* rhs){
for(int i=0; i<len(rhs);i++) {
// allow chaining of assignments. ptr[i] = rhs[i];
return *this; }
} }

CS101 Autumn 2019 @ CSE IIT Bombay 37


Assigning a String to another String
• We want to allow code such as
mystring a, b;
a = “pqr”;
b = a;
• The statement b = a; will cause a call
b.operator=(a) to be made.
• need a member function operator= which
takes a mystring as argument

CS101 Autumn 2019 @ CSE IIT Bombay 38


The code

mystring& operator=(const mystring &rhs){


// We must allow self assignment.
// If a self assignment, do nothing.
if(this == &rhs) return *this;

// Call the previous "=" operator.


*this = rhs.ptr;

return *this;
}

CS101 Autumn 2019 @ CSE IIT Bombay 39


The mystring destructor
• The destructor gets called when a myString
object goes out of scope, i.e., control exits the
block in which it is defined.
• Clearly, we must delete ptr to prevent memory
leaks.
~mystring(){
delete ptr;
}
• Note that this will work even if ptr is NULL; in
such cases delete does nothing.

CS101 Autumn 2019 @ CSE IIT Bombay 40


The copy constructor
• Copy constructor is like an assignment, except that

– we know that the destination object is also just being created, and
hence its ptr cannot be pointing to any heap variable.

– we don’t need to return anything.

• Hence this will be a simplified version of the assignment operator:

mystring(const mystring &rhs){


ptr = new char[length(rhs.ptr)+1];
scopy(ptr,rhs.ptr);
}

CS101 Autumn 2019 @ CSE IIT Bombay 41


The [] operator
• To access the individual characters of the
character string, we define operator[].
char& operator[](int i){
return ptr[i];
}
• We are returning a reference, so that we can
change characters also, i.e. write something like
mystring a; a = “pqr”;
a[0] = a[1];
• This should cause a to become “qqr”.

CS101 Autumn 2019 @ CSE IIT Bombay 42


Concatenation: + operator
• We use a+b to mean the concatenation of a, b.
mystring operator+(const String &rhs) {
mystring res; // result
// Allocate space for the result.
res.ptr = new char[length(ptr)+length(rhs.ptr)+1];
// Copy the string in the receiver into the result.
scopy(res.ptr, ptr);
// Copy the string in rhs but start at length(ptr)
// New version of scopy defined in book.
scopy(res.ptr, rhs.ptr, length(ptr));
return res;
}

CS101 Autumn 2019 @ CSE IIT Bombay 43


Remarks
• We have given the definitions of all the member
functions needed to be able to perform assignment,
passing and returning from functions, concatenation etc.
of mystring objects.

• The code given should be inserted into the definition of


mystring.

CS101 Autumn 2019 @ CSE IIT Bombay 44


Using the mystring class
• Here is a program to read 100 names and store them.

int main(){
mystring names[100];
char buffer[80]
for(int i=0; i<100; i++){
cin.getline(buffer,80);
names[i] = buffer;
}
// now use the array names[] however you want.
}

• If we use our class mystring, we do not need to mention


memory allocation, it happens automatically in the member
functions.

CS101 Autumn 2019 @ CSE IIT Bombay 45


Concluding remarks
• The class myString that we have defined performs
memory allocation and deallocation behind the scenes,
automatically.

• From the point of the user, myString variables are similar


to or as simple as int variables, except that myString
variables can contain character strings of arbitrary length
rather than integers.

• C++ Standard Library contains a class string (all


lowercase) which is a richer version of our myString
class.

CS101 Autumn 2019 @ CSE IIT Bombay 46


Templates

CS101 Autumn 2019 @ CSE IIT Bombay 47


Template functions
• Function templates (Sec 12.5 in book)
• Consider these three functions: same body, different types
int Abs(int x) float Abs(float x) double Abs(double x)
{ { {
if (x < 0) if (x < 0) if (x < 0)
return -x; return -x; return -x;
else return x; else return x; else return x;
} } }

template<typename T>
A common template to unite T Abs(T x) {
them all . . . if (x < 0)
return -x;
else return x;
}
CS101 Autumn 2019 @ CSE IIT Bombay 48
Template Class
• Like function templates, create class with templates.
template <class T> main () {
class Queue { Queue<V3> q;
int front, nWaiting; Queue<int> r;
T elements[100];
r.insert(10);
public:
bool insert(T value)
v V3(1,1,1);
{...} q.insert(v);
bool remove(T &val)
{...} }
};

CS101 Autumn 2019 @ CSE IIT Bombay 49


Vectors
• Friendlier, more versatile version of arrays
• Must include header file <vector> to use it

• vectors of any type by supplying the type as an argument to the


template
• Indexing possible like arrays

• Possible to extend length, or even insert in the middle

CS101 Autumn 2019 @ CSE IIT Bombay 50


vector examples
#include <vector> // needed

vector<int> v1; //empty vector. Elements will be int


vector<float> v2; //empty vector. Elements will be float
vector<short> v3(10); // vector of length 10.
// Elements are of type short

vector<char> v4(5,’a’); // 5 elements, all ‘a’


cout << v3.size() << endl; // prints vector length, 10
// v3.length() is same

v3[6] = 34; // standard indexing

CS101 Autumn 2019 @ CSE IIT Bombay 51


vector examples (continued)
#include <vector> // needed
...

v3.push_back(22); // append 22 to v3.


// Length increases
vector<char> w;
w = v5; // element by element copy

v1.resize(9); // change length to 9


v2.resize(5, 3.3); // length becomes 5, all
// values become 3.3
vector<string> s; // vector of string

vector<vector<int> > vv; // allowed!

CS101 Autumn 2019 @ CSE IIT Bombay 52


size_t
• The member function size returns a value of type size_t
• size_t is an unsigned integer type; it is meant specially for storing
array indices
• When going through array elements, use size_t for the index
variable
vector<double> v(10); // initialize v
for(size_t i=0; i<v.size(); i++)
cout << v[i] << endl;
• If i were declared int, then the compiler would warn about the
comparison between i and v.size()
– comparison between signed and unsigned int, which is tricky
as discussed in Section 6.8.
– By declaring i to be size_t, the warning is suppressed.

CS101 Autumn 2019 @ CSE IIT Bombay 53


Multi-dimensional vectors

vector<vector <int> > vv;


// each element of vv is itself a vector of int
// we must supply two indices to get to int
// Hence it is a 2d vector!
// Currently vv is empty

vector<vector <int> > vv1(5, vector<int>(10,23));


// vv1 has 5 elements
// each of which is a vector<int>
// of length 10,
// having initial value 23

CS101 Autumn 2019 @ CSE IIT Bombay 54


Multi-dimensional vectors usage
• Note that the syntax is not new/special
• It is merely repeated use of specifying the length and initial value:
vector<type> name(length, value)
• Two dimensional arrays can be accessed by supplying two indices,
i.e., vv1[4][6] and so on
• Write vv1.size() and vv1[0].size() to get number of rows and
columns

CS101 Autumn 2019 @ CSE IIT Bombay 55


Creating a 5x5 identity matrix

vector<vector<double>> m(5, vector<double>(5,0));


// m = 5x5 matrix of 0s
// elements of m can be accessed
// by specifying two indices
for(int i=0; i<5; i++)
m[i][i] = 1;
// place 1’s along the diagonal

CS101 Autumn 2019 @ CSE IIT Bombay 56


Ch. 22 (22.2.7)

• The book discusses a matrix class which internally uses vector


of vectors

• This class is better than two dimensional arrays because it can


be passed to functions by value or by reference, with the
matrix size being arbitrary

CS101 Autumn 2019 @ CSE IIT Bombay 57


Sorting a vector
• C++ provides a built-in facility to sort vectors and also arrays
• You must include <algorithm> to use this

vector<int> v(10);
// somehow initialize v

sort(v.begin(), v.end());

• That’s it! v is sorted in non decreasing order

• begin() and end() return “iterators” over v.


Think of them as abstract pointers to the beginning and the end.

CS101 Autumn 2019 @ CSE IIT Bombay 58


Sorting an array

• The algorithms in header file <algorithm> can also sort


arrays as follows

double a[100];
// somehow initialize a

sort(a, a+100); // sorted!


// second argument is name+length

• More variations in the book

CS101 Autumn 2019 @ CSE IIT Bombay 59


The Map Template Class
• A vector or an array give us an element when we supply an
index
– Index must be an integer
• May want to use indices which are not integers, but strings
– Given the name of a country, we may want to find out its
population, or its capital
– This can be done using a map
– (a.k.a) key-value store
– keys and values can be of data types other than integers

CS101 Autumn 2019 @ CSE IIT Bombay 60


The Map
• General form:
map<indextype, valuetype> mapname;

• Examples:
map<string, double> population;
Indices will have type string (country names), and elements
will have type double (population)

map<string, vector<string>> dictionary;

??

CS101 Autumn 2019 @ CSE IIT Bombay 61


Map usage
map<string, double> population;

population[“India”] = 1.21;
// in billions. Map entry created
population[“China”] = 1.35;
population[“USA”] = 0.31;

cout << population[“China”] << endl;


// will print 1.35

population[“India”] = 1.22;
//update allowed

CS101 Autumn 2019 @ CSE IIT Bombay 62


Checking index validity
string country;
cout << “Give country name: “;
cin >> country;

if(population.count(country)>0) {
// true if element with index = country
// was stored earlier
// count is a known member function
cout << population[country] << endl;
}
else cout << “Not known.\n”;

CS101 Autumn 2019 @ CSE IIT Bombay 63


Remarks

• A lot goes on behind the scenes to implement a map

• Basic idea is discussed in Chapter 24 of the textbook

• How to print all entries of a map?

CS101 Autumn 2019 @ CSE IIT Bombay 64


Iterators
• A map can be thought of as holding a sequence of pairs, of the
form (index, value)
• For example, the population map can be considered to be the
sequence of pairs
[(“China”,1.35), (“India”,1.21), (“USA”, 0.31)]
• You may wish to access all elements in the map, one after another,
and do something with them
• For this, you can obtain an iterator, which points to (in an abstract
sense) elements of the sequence

CS101 Autumn 2019 @ CSE IIT Bombay 65


Iterators (continued)
An iterator points to (in an abstract sense) elements of the sequence

• An iterator can be initialized to point to the first element of the


sequence
• In general, given an iterator which points to some element,
you can ask if there is any element following the element, and
if so make the iterator point to the next element

• An iterator for a map<index,value> is an object with type


map<index,value>::iterator

CS101 Autumn 2019 @ CSE IIT Bombay 66


Using iterators
• An iterator points to elements in the map; each element is a
struct with members first and second

• We can get to the members by using dereferencing

• Note that this simply means that the dereferencing operators


are defined for iterators

• If many elements are stored in an iterator, they are arranged


in (lexicographically) increasing order of the key

CS101 Autumn 2019 @ CSE IIT Bombay 67


Example
map<string,double> population;
population[“India”] = 1.21;

map<string,double>::iterator mi;
mi = population.begin();
// population.begin() : constant iterator
// points to the first element of population
// mi points to (India,1.21)

cout << mi->first << endl; // or (*mi).first << endl;


// will print out India

cout << mi->second << endl;


// will print out 1.21

CS101 Autumn 2019 @ CSE IIT Bombay 68


Example
map<string,double> population;
population[“India”] = 1.21;
population[“China”] = 1.35;
population[“USA”] = 0.31;

for(map<string,double>::iterator
mi = population.begin();
mi != population.end(); mi++)

// population.end() : constant iterator


// marking the end of population
// ++ sets mi to point to the
// next element of the map
// loop body

CS101 Autumn 2019 @ CSE IIT Bombay 69


Example
map<string,double> population;
population[“India”] = 1.21;
population[“USA”] = 0.31;
population[“China”] = 1.35;

for(map<string,double>::iterator
mi = population.begin();
mi != population.end();
mi++)
{
cout << (*mi).first << “: “ << (*mi).second << endl;
// or cout << mi->first << “: “ << mi->second << endl;
}
// will print out countries and population in
alphabetical order

CS101 Autumn 2019 @ CSE IIT Bombay 70


Remarks

• Iterators can work with vectors and arrays too


• Iterators can be used to find and delete elements from maps
and vectors.

map<string,double>::iterator
mi = population.find("India");

population.erase(mi);

CS101 Autumn 2019 @ CSE IIT Bombay 71


Maps with user-defined class as index
• Any class used as indextype on a map must implement
the "<" operator.
• Example, the following code will not work because "<" is
not defined on V3.
• class V3 {public: double x,y,z};
• map<V3, string> vec2string;
• A correct implementation of V3 may be something like:
class V3 {
public:
double x,y,z;
bool operator<(const V3& a) const {
if (x < a.x) return true;
if (x == a.x && y < a.y) return true;
if (x==a.x && y == a.y && z < a.z) return true;
return false;
}
};
CS101 Autumn 2019 @ CSE IIT Bombay 72
Sets
• Sets are containers that store unique elements following a specific
order
• The value of the elements in a set cannot be modified once in the
container (the elements are always const), but they can be
inserted or removed from the container
• Internally, the elements in a set are always sorted following a
specific ordering criterion indicated by its internal comparison
object

CS101 Autumn 2019 @ CSE IIT Bombay 73


Populating and Traversing a Set
#include <set> // set class library
...
set<int> set1; // create a set object,
// specifying its content as int
// the set is empty
int ar[]={3,2,4,2};
for (int i = 0; i < 4; i++) {
set1.insert(ar[i]); // add elements to the set.
}
for (set<int>::iterator iter = set1.begin();
iter != set1.end(); iter++) {
cout << *iter << " ";
} // prints 2 3 4

CS101 Autumn 2019 @ CSE IIT Bombay 74


Application of Set
Given N students where each student has a list of courses that they have taken.
Create group of all students that have taken exactly the same set of courses.

map<set<string>, vector<int>> study_group;


// key of the map is the set of courses.
// value is vector of student roll-numbers of students
// who have taken this course.

cin >> N;
for(int i = 0; i < N; i++) {
int roll, int n;
cin >> roll >> n;
set<string> subjects;

CS101 Autumn 2019 @ CSE IIT Bombay 75


Application of Set (continued)
for (int j = 0; j < n; j++) {
string s; cin >> s;
subjects.insert(s);
}
study_group[subjects].push_back(rollno);
}

CS101 Autumn 2019 @ CSE IIT Bombay 76


List
• Implements a classic list data structure
• Supports a dynamic bidirectional linear list
• Unlike a C++ array, the objects the STL list contains cannot be
accessed directly (i.e., by subscript)
• Is defined as a template class, meaning that it can be customized to
hold objects of any type
• Responds like an unsorted list (i.e., the order of the list is not
maintained).
However, there are functions available for sorting the list

CS101 Autumn 2019 @ CSE IIT Bombay 77


Populating and Traversing a List
#include <list> // list class library
...
list <int> list1; // create a list object,
// specifying its content as int
// the list is empty
for (i=0; i<5; i++)
list1.push_back (i); // add at the end of the list
...
while (list1.size() > 0)
{ cout << list1.front(); // print the front item
list1.pop_front(); // discard the front item
}
// other functions
// insert, remove, pop_back, push_front, remove, sort, …

CS101 Autumn 2019 @ CSE IIT Bombay 78


Concluding Remarks
• Standard Library contains other useful classes, e.g. queue, list, set
etc.
• The Standard Library classes use heap memory, however this
happens behind the scenes and you don’t have to knowabout it

• The library classes are very useful. Get some practice with them

More details on the web.


Example:http://www.cplusplus.com/reference/stl/

CS101 Autumn 2019 @ CSE IIT Bombay 79

You might also like