CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part...

26
CSIS 123A Lecture 6 Strings & Dynamic Memory

Transcript of CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part...

Page 1: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

CSIS 123A Lecture 6

Strings & Dynamic Memory

Page 2: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Introduction To The string Class

• Must include <string>– Part of the std library

• You can declare an instance like any other class– string str;

• Notice string is lower case• = operator is overloaded so you can set

strings– str = “Hello World”;

• Can also be initialized as it is declared– string str = “Hello World”;– Or std::string str = “Hello World”;

Page 3: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Has Friend functions

• You can use cin and cout with strings– << and >> are friends of the class

#include <iostream>#include <string>using namespace std;int main(){string s; cin >> s;cout << s << endl;

}

Page 4: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Useful Operators

• + allows you to concatenate strings– string s1 = “Hello “ ;– string s2 = “ World”;– string s3 = s1 + s2; // s3 now has “Hello

World”

• += Short cut for concatenating– s1+= s2;

Page 5: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Equality Operators• Produce true or false values

string s1 = “Hello”;string s2 = “World”;s1 == s2 ; // produces falses1 != s2 ; // produces trues1 > s2; // produces false because W is greater in ascii than Hs1 < s2; // produces true for the same reason as above

• Also have • <= less than or equal• >= greater than or equal

Page 6: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Can be treated like an array• The subscript operator can be used to

return a characterstring str = “ABC”;char c = str[1]; // c now holds B

• Can also set a characterstring str = “ABC”;str[1] = ‘Z’; // str now has AZC

• Be careful setting characters• Make sure the string has some space first

string str;str[1] = ‘x’; // Not a good ideastr = “Hello”;str[1] = ‘a’; // works ok str now holds hallo

Page 7: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Useful Member Functions• length() & size () functions

– Both return the number of charactersstring str = "Hello";cout << str.size() << endl; // both output 5cout << str.length() << endl;

• c_str() returns a null terminated array of chars• A c string! Useful for older library functions that don’t

know what a string is

• erase(int start, int length);string str = "abcdefghi"; str.erase (5,3); cout << str12 << endl; // yields "abcdei"

Page 8: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

find & rfind

• find(string &find, size_t pos) searches for the first occurrence of a string starting at pos.

• Returns the position of the 1st character of the found string

string s = “abcdefghi”string s1 = “def”;int pos = s.find(s1, 0); // returns the position of d in the string 3 in this case

• rfind does the same as find except that it finds the last occurrence

Page 9: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

substr functions

• substr(int pos, int length)

• Returns a substring of the current string starting at pos with the specified length

string str = “abcdefghi”;string str1 = str.substr(6, 2); // str1 now holds “gh”

Page 10: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

The getline function• getline(istream &is, string &str, char delim = ‘\n’);• Reads characters from an input stream into a

string, stopping when one of the following things happens:– An end-of-file condition occurs on the input

stream – When the maximum number of characters that

can fit into a string have been read – When a character read in from the string is equal

to the specified delimiter (newline is the default delimiter); the delimiter character is removed from the input stream, but not appended to the string.

Page 11: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

More getline

• Returns a reference to the input stream. – If the stream is tested as a logical value (as in an if

or while), it is equivalent to true if the read was successful and false otherwise (e.g., end of file).

• The most common use of this function is to do "line by line" reads from a file.

• Remember that the normal extraction operator (>>) stops on white space, not necessarily the end of an input line.

• The getline function can read lines of text with embedded spaces.

Page 12: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

getline example#include <iostream>#include <vector>#include <string>using namespace std;

Int main(){vector<string> vec1;string line;

vec1.clear(); ifstream infile ("stl2in.txt"); while (getline(infile,line,'\n')) { vec1.push_back (line); }

}

Page 13: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Dynamic memory allocation

• Until now, in our programs, we have only had as much memory as we have requested in declarations of variables– Array sizes have been fixed

• Not good because data in programs can grow and shrink as they run

• How do we dynamically allocate memory?– Through the use of new and delete operators

Page 14: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

new • When we want to create memory we can

do so with newint *myArray; myArray = new int [5];

• Operating system will create a space in memory to hold 5 ints and return a pointer to the memory

Page 15: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

What’s the difference

• Without new arrays size must be a constant – Means we need to decide size of arrays at

design time not execution time• dynamic memory allocation allows assigning

memory during the execution of the program using any variable, constant or combination of both as size.

Page 16: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Who manages memory• The dynamic memory is generally managed

by the operating system– in multitasking interfaces it can be shared

between several applications.• There is a possibility that the memory can be

depleted. – If the operating system cannot allocate the requested

memory, it returns a null pointer. – This means you should check for it:

int *myArraymyArray = new int [5]; if (myArray == NULL) { // error assigning memory. Take measures. };

Page 17: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

The delete operator

• Once memory is no longer needed it should be freed – Make it available for future requests of

dynamic memory. – The operator delete exists for this purpose,

whose form is:

Page 18: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

An Exampleinclude <iostream>#include <cstdlib> using namespace std;int main (){char input [100];int i,n;long *pArray;cout << "How many numbers do you want to type in? ";cin >> i;pArray = new long[i];if (pArray == NULL) exit (1);for (n=0; n<i; n++){ cout << "Enter number: "; cin >> pArray[n];}cout << "You have entered: ";for (n=0; n<i; n++) cout << pArray[n] << ", ";delete[] pArray;return 0;}

Page 19: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Memory Leaks• Happens when you forget to free a block

of memory allocated with the new operator or when you make it impossible to do so

• As a consequence your application may eventually run out of memory and may even cause the system to crash.

Page 20: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Leak example 1• Deleting memory before reallocating it

char *string; string = new char[20]; string = new char[30]; delete [] string;

How can we fix it and what exactly is the problem?

Page 21: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Leak example 2• Be sure to have a pointer to each dynamic

variable:char *first_string = new char[20];char *second_string = new char[20];strcpy(first_string, "leak");second_string = first_string;strcpy(second_string, first_string);delete [] second_string;

What happened is that the address of the dynamic variable associated with second_string (as a side-effect of the pointer assignment) is lost so we cannot delete it from the heap anymore. Thus the last line of code only frees the dynamic variable associated with first_string, which is not what we wanted.

Page 22: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Leak Example 3• Local pointers:

void leak() { int k; char *cp = new char('E'); delete cp;}

• What happens of cp is not deleted?• It seems that it would be destroyed when the

function returns• Actually the pointer is but not it’s memory

Page 23: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Singleton Classes

• Occasionally you want to create class that doesn’t need multiple instances– Address Book may be one of these

• Big question is why?– Allows you to get a reference to the single

instance that was created• Can be from anywhere

Page 24: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

The static pointer• Singleton class uses a static pointer to

access the instance of the object– Remember static variables are declared on the

heap • Hold there value through the life of the program

– Defined as follows:

class addressBook{

private: static addressBook *pInstance;

}

Page 25: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

Accessor Method

• Once you have created the static pointer– You need to create a public accessor method

to retrieve the pointer:

class addressBook{private: static addressBook *pInstance;public: static addressBook *Instance();

}

Page 26: CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.

And the function Body

• Notice the declaration before the function– This is needed to create the pointer

addressBook * addressBook::pInstance = NULL;addressBook *addressBook::Instance(){

if(pInstance == NULL){

pInstance = new addressBook;}return pInstance;

}