CS 101: Computer Programming and Utilization Puru with CS101 TAs - - PowerPoint PPT Presentation

cs 101
SMART_READER_LITE
LIVE PREVIEW

CS 101: Computer Programming and Utilization Puru with CS101 TAs - - PowerPoint PPT Presentation

CS 101: Computer Programming and Utilization Puru with CS101 TAs and Staff Course webpage: https://www.cse.iitb.ac.in/~cs101/ Lecture 21: The C++ Standard Library CS101 Autumn 2019 @ CSE IIT Bombay Object Oriented Programming A methodology


slide-1
SLIDE 1

CS101 Autumn 2019 @ CSE IIT Bombay

CS 101: Computer Programming and Utilization

Puru

with CS101 TAs and Staff Course webpage: https://www.cse.iitb.ac.in/~cs101/

Lecture 21: The C++ Standard Library

slide-2
SLIDE 2

CS101 Autumn 2019 @ CSE IIT Bombay

Object Oriented Programming

A methodology for designing programs

Chapter 17, 18

2

slide-3
SLIDE 3

CS101 Autumn 2019 @ CSE IIT Bombay

The C++ structure

  • Member variables

− Basic facility provided in C++ to conveniently gather together information associated with an entity − Inherited from the C language

  • Member functions

− New feature introduced in C++ − Actions/operations that effect the entity − User defined data type with variables and functions

3

slide-4
SLIDE 4

CS101 Autumn 2019 @ CSE IIT Bombay

Objects As Software Components

  • A software component can be built around a struct
  • Just as a hardware component is useful for building big hardware

systems, so is a software component for building large software systems

  • A software component must be convenient to use, and also safe,

i.e., help in preventing programming errors

4

slide-5
SLIDE 5

CS101 Autumn 2019 @ CSE IIT Bombay

The modern version of a struct

  • Designer of the struct decides what happens during execution of

standard operations such as: – Creation of the object – Assignment – Passing the object to a function – Returning the object from a function – Destroying the object when it is not needed

5

slide-6
SLIDE 6

CS101 Autumn 2019 @ CSE IIT Bombay

C++ specifics of structures, classes and objects

  • Constructors
  • Copy Constructors
  • Destructors
  • Operator overloading
  • Overloading the assignment operator
  • Access control
  • Classes
  • Graphics and input/output classes

6

slide-7
SLIDE 7

CS101 Autumn 2019 @ CSE IIT Bombay

Constructor for V3

struct V3{ double x,y,z; V3(){ x = y = z = 0; } V3(double a){ x = y = z = a; } }; int main(); V3 v1(5), v2; }

  • When defining v1, an argument is

given

  • So the constructor taking a single

argument is called. Thus each component of v1 is set to 5

  • When defining v2, no argument is

given.

  • So the constructor taking no

arguments gets called. Thus each component of v2 is set to 0

7

slide-8
SLIDE 8

CS101 Autumn 2019 @ CSE IIT Bombay

Copy Constructor of Queue

struct Queue{ int elements[N], nWaiting, front; Queue(const Queue &source){ // Copy constructor front = source.front; nWaiting = source.nWaiting; for(int i=front, j=0; j<nWaiting; j++){ elements[i] = source.elements[i]; i = (i+1) % N; } };

8

slide-9
SLIDE 9

CS101 Autumn 2019 @ CSE IIT Bombay

Destructor Example

struct Queue{ int elements[N], nWaiting, front; . . . ~Queue(){ //Destructor if(nWaiting>0) cout << “Warning:” <<“ non-empty queue being destroyed.” << endl; } };

9

slide-10
SLIDE 10

CS101 Autumn 2019 @ CSE IIT Bombay

Operator Overloading

  • In Mathematics, arithmetic operators are used with numbers, but

also other objects such as vectors

  • Something like this is also possible in C++!
  • An expression such as x @ y where @ is any “infix” operator is

considered by C++ to be equivalent to x.operator@(y) in which operator@ is a member function

  • If the member function operator@ is defined, then that is called to

execute x @ y

10

slide-11
SLIDE 11

CS101 Autumn 2019 @ CSE IIT Bombay

Example: Arithmetic on V3 objects

struct V3{ double x, y, z; V3(double a, double b, double c){ x=a; y=b; z=c; } V3 operator+(V3 b){ // adding two V3s return V3(x+b.x, y+b.y, z+b.z); // constructor call } V3 operator*(double f){ // multiplying a V3 by f return V3(x*f, y*f, z*f); // constructor call } };

11

slide-12
SLIDE 12

CS101 Autumn 2019 @ CSE IIT Bombay

Using V3 Arithmetic

int main(){ V3 u(1,2,3), a(4,5,6), s; double t=10; s = u*t + a*t*t*0.5; cout << s.x <<‘ ‘<< s.y << ‘ ‘<< s.z << endl; }

12

slide-13
SLIDE 13

CS101 Autumn 2019 @ CSE IIT Bombay

Pointers to Structures

  • Disk d1={{2,3},4}, *dptr;
  • *dptr is defined to have type Disk, so dptr is a pointer to a variable
  • f type Disk
  • Normal pointer operations are allowed on structure pointers
  • dptr = &d1;
  • (*dptr).radius = 5; //changes the radius of d1
  • Operator ->

– (*x).y is same as x->y

  • dptr->radius = 5; // same effect as above

13

slide-14
SLIDE 14

CS101 Autumn 2019 @ CSE IIT Bombay

Pointers as Structure Members

struct Disk2{ double radius; Point *centerptr; } Point p={10,20}; Disk2 d; d.centerptr = &p; cout << d.centerptr->x << endl; // will print 10.

14

slide-15
SLIDE 15

CS101 Autumn 2019 @ CSE IIT Bombay

The this Pointer

  • So far, we have not provided a way to refer to the receiver itself inside the

definition of a member function.

  • Within the body of a member function, the keyword this points to the receiver

i.e., the struct on which the member function has been invoked.

  • Trivial use: write this->member instead of member directly

struct V3{ double x, y, z; double length(){ return sqrt(this->x * this->x + this->y * this->y + this->z * this->z); } }

  • More interesting use later.

15

slide-16
SLIDE 16

CS101 Autumn 2019 @ CSE IIT Bombay

Overloading The Assignment Operator

  • Normally if you assign one struct to another, each member of the

rhs is copied to the corresponding member of the lhs

  • You can change this behaviour by defining member function
  • perator= for the struct
  • A return type must be defined if you wish to allow chained

assignments, i.e., v1 = v2 = v3; which means v1 = (v2 = v3); – The operation must return a reference to the left hand side

  • bject

16

slide-17
SLIDE 17

CS101 Autumn 2019 @ CSE IIT Bombay

Example

struct Queue{ ... Queue& operator=(Queue &rhs){ front = rhs.front; nWaiting = rhs.nWaiting; for(int i=0; i<nWaiting; i++){ elements[i] = rhs.elements[i]; i = (i+1) % N; } return *this; } }; // only the relevant elements are copied

17

slide-18
SLIDE 18

CS101 Autumn 2019 @ CSE IIT Bombay

Access Control

  • It is possible to restrict access to members or member functions of

a struct

  • Members declared public: no restriction
  • Members declared private: Can be accessed only inside the

definition of the struct

  • Typical strategy

Declare all data members to be private, and some subset of function members to be public

18

slide-19
SLIDE 19

CS101 Autumn 2019 @ CSE IIT Bombay

Access Control Example

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

19

slide-20
SLIDE 20

CS101 Autumn 2019 @ CSE IIT Bombay

Remarks

  • public:, private: : access specifiers
  • An access specifier applies to all members defined following it,

until another specifier is given

  • Thus elements, nWaiting, front are private, while Queue(),

insert, remove are public

20

slide-21
SLIDE 21

CS101 Autumn 2019 @ CSE IIT Bombay

Remarks

  • The default versions of the constructor, copy constructor,

destructor, assignment operator are public

  • If you specify any of these as private, then they cannot be invoked
  • utside of the struct definition
  • Thus if you make the copy constructor of a struct X private, then

you will get an error if you try to pass a struct of type X by value

  • Thus, as a designer of a struct, you can exercise great control over

how the struct gets used

21

slide-22
SLIDE 22

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

22

slide-23
SLIDE 23

CS101 Autumn 2019 @ CSE IIT Bombay

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.

23

slide-24
SLIDE 24

CS101 Autumn 2019 @ CSE IIT Bombay

Function definition and declaration (with class)

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

24

slide-25
SLIDE 25

CS101 Autumn 2019 @ CSE IIT Bombay

Example (with struct)

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

25

slide-26
SLIDE 26

CS101 Autumn 2019 @ CSE IIT Bombay

Concluding Remarks

  • The notion of a packaged software component is important.
  • Making data members private

– hiding the implementation from the user

  • Making some member functions public:

– providing an interface using which the object can be used

  • Separation of the concerns of the developer and the user

– The specification of the function must be clearly written down (analogous to interface) – The user should not worry about how the function does its work (analogous to hiding data members)

26

slide-27
SLIDE 27

CS101 Autumn 2019 @ CSE IIT Bombay

The C++ Standard (Template) Library Chapter 22

27

slide-28
SLIDE 28

CS101 Autumn 2019 @ CSE IIT Bombay

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 …

28

slide-29
SLIDE 29

CS101 Autumn 2019 @ CSE IIT Bombay

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

29

slide-30
SLIDE 30

CS101 Autumn 2019 @ CSE IIT Bombay

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

  • fstream 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;

  • utfile << v;

} // f1.txt must begin with 10 numbers. These will be read and // written to file f2.txt }

30

slide-31
SLIDE 31

CS101 Autumn 2019 @ CSE IIT Bombay

ifstream /ofstream member functions

  • open, close, is_open
  • >> , <<, !
  • get, getline, peek, read
  • put, write

31

slide-32
SLIDE 32

CS101 Autumn 2019 @ CSE IIT Bombay

“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’

32

slide-33
SLIDE 33

CS101 Autumn 2019 @ CSE IIT Bombay

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
  • f string
  • no end of string can lead to chaos!

33

slide-34
SLIDE 34

CS101 Autumn 2019 @ CSE IIT Bombay

Challenge with char arrays!

  • Have to ensure null-termination at all points
  • Character array sizing has to be managed (via copies

etc.) explicitly

  • Not objects!

34

char str[6] = {‘e’, ‘a’, ‘r’, ‘t’, ‘h’} ; cout << str; // early takeoff of space shuttle str[5] = ‘\0’; cout << str; // back to earth!

slide-35
SLIDE 35

CS101 Autumn 2019 @ CSE IIT Bombay

the string class

  • can use indexing as in arrays
  • other member functions

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

35

string str = “earth”; cout << str; // stay on earth!

slide-36
SLIDE 36

CS101 Autumn 2019 @ CSE IIT Bombay

Printing a string in reverse

string message; getline(cin, message); int mx = message.size()-1; while (mx >= 0) { cout << message[mx];

  • -mx;

}

  • mx updated in a predictable way
  • Ideal candidate to write as for loop

Character at position mx in string message

36

slide-37
SLIDE 37

CS101 Autumn 2019 @ CSE IIT Bombay

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

37

slide-38
SLIDE 38

CS101 Autumn 2019 @ CSE IIT Bombay

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 } }

38

slide-39
SLIDE 39

CS101 Autumn 2019 @ CSE IIT Bombay

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 } // ends needles loop }

Generalize to work in case needles can also have repeated characters

39

slide-40
SLIDE 40

CS101 Autumn 2019 @ CSE IIT Bombay

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)

40

slide-41
SLIDE 41

CS101 Autumn 2019 @ CSE IIT Bombay

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.

41

slide-42
SLIDE 42

CS101 Autumn 2019 @ CSE IIT Bombay

  • Function templates (Sec 12.5 in book)
  • Consider these three functions: same body, different types

int Abs(int x) { if (x < 0) return -x; else return x; } float Abs(float x) { if (x < 0) return -x; else return x; } double Abs(double x) { if (x < 0) return -x; else return x; }

A common template to unite them all....

template<typename T> T Abs(T x) { if (x < 0) return -x; else return x; }

Template functions

42

slide-43
SLIDE 43

CS101 Autumn 2019 @ CSE IIT Bombay

  • Like function templates, create class with templates.

template <class T> class Queue { int front, nWaiting; T elements[100]; public: bool insert(T value) {...} bool remove(T &val) {...} }; main () { Queue<V3> q; Queue<int> r; }

Template Class

43

slide-44
SLIDE 44

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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

Vectors

44

slide-45
SLIDE 45

CS101 Autumn 2019 @ CSE IIT Bombay

#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

vector examples

45

slide-46
SLIDE 46

CS101 Autumn 2019 @ CSE IIT Bombay

#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!

vector examples (continued)

46

slide-47
SLIDE 47

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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.

size_t

47

slide-48
SLIDE 48

CS101 Autumn 2019 @ CSE IIT Bombay

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

Multi-dimensional vectors

48

slide-49
SLIDE 49

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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

Multi-dimensional vectors usage

49

slide-50
SLIDE 50

CS101 Autumn 2019 @ CSE IIT Bombay

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

Creating a 5x5 identity matrix

50

slide-51
SLIDE 51

CS101 Autumn 2019 @ CSE IIT Bombay

Remarks

  • The book discusses a matrix class which internally uses vector
  • f 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

  • Ch. 22 (22.2.7)

51

slide-52
SLIDE 52

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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 are “iterators” over v. Think of them as

abstract pointers to the beginning and the end.

Sorting a vector

52

slide-53
SLIDE 53

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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

Sorting an array

53

slide-54
SLIDE 54

CS101 Autumn 2019 @ CSE IIT Bombay

  • A vector or an array give us an element when we supply an

index – Index must be an integer

  • Sometimes we 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

The Map Template Class

54

slide-55
SLIDE 55

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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; Maps words to their meanings expressed as a vector of other words.

The Map

55

slide-56
SLIDE 56

CS101 Autumn 2019 @ CSE IIT Bombay

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

Map usage

56

slide-57
SLIDE 57

CS101 Autumn 2019 @ CSE IIT Bombay

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”;

Checking index validity

57

slide-58
SLIDE 58

CS101 Autumn 2019 @ CSE IIT Bombay

  • A lot goes on behind the scenes to implement a map
  • Basic idea is discussed in Chapter 24 of our book
  • If you wish to print all entries stored in a map, you will need

to use iterators, discussed next

Remarks

58

slide-59
SLIDE 59

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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

Iterators

59

slide-60
SLIDE 60

CS101 Autumn 2019 @ CSE IIT Bombay

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

Iterators (continued)

60

slide-61
SLIDE 61

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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

Using iterators

61

slide-62
SLIDE 62

CS101 Autumn 2019 @ CSE IIT Bombay

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

Example

62

slide-63
SLIDE 63

CS101 Autumn 2019 @ CSE IIT Bombay

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

63

Example

slide-64
SLIDE 64

CS101 Autumn 2019 @ CSE IIT Bombay

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

64

Example

slide-65
SLIDE 65

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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);

65

Remarks

slide-66
SLIDE 66

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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; } };

Maps with user-defined class as index

66

slide-67
SLIDE 67

CS101 Autumn 2019 @ CSE IIT Bombay

Sets

  • Sets are containers that store unique elements following a specific
  • rder
  • 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

  • bject

67

slide-68
SLIDE 68

CS101 Autumn 2019 @ CSE IIT Bombay

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

68

slide-69
SLIDE 69

CS101 Autumn 2019 @ CSE IIT Bombay

Application of Set

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;

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.

69

slide-70
SLIDE 70

CS101 Autumn 2019 @ CSE IIT Bombay

Application of Set (continued)

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

70

slide-71
SLIDE 71

CS101 Autumn 2019 @ CSE IIT Bombay

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 (ie. the order of the list is not

maintained). However, there are functions available for sorting the list

71

slide-72
SLIDE 72

CS101 Autumn 2019 @ CSE IIT Bombay

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 }

72

slide-73
SLIDE 73

CS101 Autumn 2019 @ CSE IIT Bombay

  • 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/

Concluding Remarks

73