1 / 26

CSIS 123A Lecture 6

CSIS 123A Lecture 6. Strings & Dynamic Memory. 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”;

Download Presentation

CSIS 123A Lecture 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSIS 123A Lecture 6 Strings & Dynamic Memory

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

  3. Has Friend functions #include <iostream>#include <string>using namespace std; int main(){string s; cin >> s;cout << s << endl; } • You can use cin and cout with strings • << and >> are friends of the class

  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 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 Produce true or false values

  6. Can be treated like an array 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 The subscript operator can be used to return a character

  7. Useful Member Functions 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" • length() & size () functions • Both return the number of characters

  8. find & rfind 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 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

  9. substr functions string str = “abcdefghi”;string str1 = str.substr(6, 2); // str1 now holds “gh” substr(int pos, int length) Returns a substring of the current string starting at pos with the specified length

  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. • The getline function can read lines of text with embedded spaces.

  12. 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); • } • }

  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 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 When we want to create memory we can do so with new

  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 int *myArraymyArray = new int [5]; if (myArray == NULL) { // error assigning memory. Take measures.   }; • 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:

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

  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 char *string; string = new char[20]; string = new char[30]; delete [] string; How can we fix it and what exactly is the problem? Deleting memory before reallocating it

  21. Leak example 2 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. Be sure to have a pointer to each dynamic variable:

  22. Leak Example 3 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 Local pointers:

  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 addressBook * addressBook::pInstance = NULL; addressBook *addressBook::Instance() { if(pInstance == NULL) { pInstance = new addressBook; } return pInstance; } • Notice the declaration before the function • This is needed to create the pointer

More Related