Download presentation
Presentation is loading. Please wait.
Published byMarjory Simon Modified over 9 years ago
1
CSIS 123A Lecture 6 Strings & Dynamic Memory
2
Introduction To The string Class Must include –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”;
3
Has Friend functions You can use cin and cout with strings – > are friends of the class #include #include using namespace std; int main() { string s; cin >> s; cout << s << endl; }
4
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;
5
Equality Operators Produce true or false values string s1 = “Hello”; string s2 = “World”; s1 == s2 ; // produces false s1 != s2 ; // produces true s1 > s2; // produces false because W is greater in ascii than H s1 < s2; // produces true for the same reason as above Also have <= less than or equal >= greater than or equal
6
Can be treated like an array The subscript operator can be used to return a character string str = “ABC”; char c = str[1]; // c now holds B Can also set a character string 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 idea str = “Hello”; str[1] = ‘a’; // works ok str now holds hallo
7
Useful Member Functions length() & size () functions –Both return the number of characters string str = "Hello"; cout << str.size() << endl; // both output 5 cout << 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"
8
find & rfind find(string &find, size_t pos) searches for the first occurrence of a string starting at pos. Returns the position of the 1 st 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
9
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”
10
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.
11
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.extraction operator The getline function can read lines of text with embedded spaces.
12
getline example #include using namespace std; Int main() { vector vec1; string line; vec1.clear(); ifstream infile ("stl2in.txt"); while (getline(infile,line,'\n')) { vec1.push_back (line); }
13
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
14
new When we want to create memory we can do so with new int *myArray; myArray = new int [5]; Operating system will create a space in memory to hold 5 ints and return a pointer to the memory
15
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.
16
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 *myArray myArray = new int [5]; if (myArray == NULL) { // error assigning memory. Take measures. };
17
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:
18
An Example include #include using namespace std; int main () { char input [100]; int i,n; long *pArray; cout > i; pArray = new long[i]; if (pArray == NULL) exit (1); for (n=0; n > pArray[n]; } cout << "You have entered: "; for (n=0; n<i; n++) cout << pArray[n] << ", "; delete[] pArray; return 0; }
19
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.
20
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?
21
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.
22
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
23
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
24
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; }
25
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(); }
26
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; }
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.