lists and strings chapter 6. objectives discuss general list abstract data type. implement class...

66
Lists and Strings Chapter 6

Upload: augusta-washington

Post on 05-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Lists and Strings

Chapter 6

Page 2: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Objectives

• Discuss general list abstract data type.• Implement class templates.• Implement the general list three different

ways.– Contiguous– Simply linked list– Doubly linked list

• Implement a string library.• Combine the string and list libraries to create

a file editing program.

Page 3: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Homework Overview

• Written (max 8 points)– 6.1 E1 (4 pts)– 6.1 E4 (4 pts)– 6.1 E7 (4 pts)

• Programming (max 30 points)– 6.3 E1(a, d) (8 pts)– 6.3 E2 (8 pts)– 6.3 E3 (a ,b, c) (10 pts)– 6.4 P1 (15 pts)

• Group Projects (55 points)– 6.2 E1, P1 (15 pts)– 6.2 E3 (c, e, i, l), E4, P3(b) (20 pts)– 6.2 E5 (c, e, i, l, m), P3(c) (20 pts)

Page 4: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

General Lists

• In a general list operations can take place at any point, not just the beginning and end.

• A list of elements is a finite sequence of elements that supports the following operations:– Construct and empty list.– Determine if the list is empty.– Determine if the list is full.– Find the size of the list.– Clear the list.– Insert an entry at a specified position.– Remove an entry from a specified position.– Retrieve the data from the entry at a specified position.– Replace an entry at a specified position.– Traverse the list, performing a given operation on each entry.

Page 5: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Specifying a Position

• To specify a location in the list we will indicate its position with an integer 0 through size-1 (similar to indexing).

• The methods will have the following signatures:– List::List();– void List::clear();– bool List::empty() const;– bool List::full() const;– int List::size() const;– Error_code List::insert(int position, const List_entry &x);– Error_code List::remove(int position, List_entry &x);– Error_code List::retrieve(int position, List_entry &x) const;– Error_code List::replace(int position, const List_entry &x);– void List::traverse(void (*visit)(List_entry &));

• Notice that traverse takes a function pointer as a parameter.– This function will be applied to every entry in the list.– Note the book uses the pointer notation – this could be

done without using pointer notation.

Page 6: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Homework – Section 6.1 (page 217)

• Written– E1 (written on paper, use calls to the

methods described in the book.) (4 pts)– E4 (written on paper) (4 pts)– E7 (written on paper) (4 pts)

Page 7: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Class Templates

• Rather than use a typedef to set to the data to be stored in the list, it is cleaner to use class templates.

• The class will look like the following:template <class List_entry>class List {

.

.

.

};• The methods will have the following form:template <class List_entry>int List<List_entry>::size() const{

.

.

.};

Page 8: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Implementation Options

There are 3 options to implement our list class.1. A contiguous implementation.– Simple to implement.– Insertions and removals are slow – similar to a

queue.

2. A simply linked list.– Similar to a stack or queue.

3. A doubly linked list.– More on this later.

Page 9: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Contiguous List Class

enum Error_code {success, fail, overflow, range_err}; // The possible error conditions

const int max_list = 10; // Use a small value for testing

template <class List_entry>class List {public:

List(); // constructor/* Stub */

int size() const;/* Post: Return the size of the List. */

bool full() const;/* Stub */

bool empty() const;/* Stub */

void clear();/* Stub */

Page 10: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Contiguous List Class

void traverse(void (*visit)(List_entry &));/* Post: The function *visit is applied to every entry in the list. */

Error_code retrieve(int position, List_entry &x) const;/* Stub */

Error_code replace(int position, const List_entry &x);/* Stub */

Error_code remove(int position, List_entry &x);/* Stub */

Error_code insert(int position, const List_entry &x);/* Post: If the List is not full and 0 <= position <= count the function

succeeds. Any entry formerly at position and all later entries have their position increased by 1 and x is inserted at position of the List. Else: the function fails with a diagnostic error code. */

protected:int count;List_entry entry[max_list];

};

Page 11: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Contiguous List Methods

template <class List_entry>Error_code List<List_entry>::insert(int position, const List_entry &x)/* Post: If the List is not full and 0 <= position <= count the

function succeeds. Any entry formerly at position and all later entries have their position increased by 1 and x is inserted at position of the List. Else: the function fails with a diagnostic error code. */

{if (full())

return overflow;if (position < 0 || position > count)

return range_err;for (int i = count - 1; i >= position; i--)

entry[i + 1] = entry[i];entry[position] = x;count++;return success;

}

Page 12: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Contiguous List Methods

template <class List_entry>int List<List_entry>::size() const/* Post: Return the size of the List. */{

return count;}

template <class List_entry>void List<List_entry>::traverse(void (*visit)(List_entry &))/* Post: The function *visit is applied to every entry in the

list. */{

for(int i = 0; i < count; i++){(*visit)(entry[i]);

}}

• Note the stubs have been omitted.

Page 13: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

List Driver Program

typedef char List_entry;

int main()/* Post: Accepts commands from user as a menu-driven demonstration program for the class List. Uses: The class List and the funcitons introduction, get_command, and

do_command. */{

List<List_entry> test_list;introduction();while (do_command(get_command(), test_list));

}

Page 14: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

List Driver Programvoid help()/* Post: A help screen for the program is printed, giving the meaning of each command that the user may enter.*/{

cout << endl << "This program allows the user to enter one command" << endl

<< "(but only one) on each input line." << endl << "For example, if the command G is entered, then" << endl << "the program will retreive an entry from the list." << endl << endl << "The valid commands are:" << endl << "I - Insert a entry into the list" << endl << "D - Delete an entry from the list" << endl << "R - Replace an entry in the list" << endl << "G - Get an entry from the list" << endl << "P - Print the list" << endl << "H - This help screen" << endl << "Q - Quit" << endl << "Press < Enter > to continue." << flush;

char c;cin.get(c); // flush out an extra newlinedo { cin.get(c);} while (c != '\n');

}

Page 15: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

List Driver Programchar get_command()/* Post: The user enters a command (I, D, R, G, P, H, Q, i, d, r, g, p, h, or q).

The function returns the command entered. */{

char command;bool waiting = true;cout << "Select command and press < Enter > :";while (waiting){ cin >> command;

command = tolower(command);if (command == 'i' || command == 'd' || command == 'r' || command == 'g' || command == 'p' || command == 'h' || command == 'q')

waiting = false; else {

cout << "Please enter a valid command:" << endl << "[I]insert [D]delete [R]replace" << endl << "[G]get [P]print [H]Help" << endl << "[Q]uit." << endl;

}}return command;

}

Page 16: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

List Driver Programbool do_command(char c, List<List_entry> &test_list)/* Pre: c represents a valid command. Post: Performs the given command c on the List test_list.

Returns false if c == 'q', otherwise returns true. Uses: The class List. */{

bool continue_input = true;int position;List_entry x;Error_code err;switch (c) {case 'i':

cout << "Please enter a position to insert the new entry: " << flush;cin >> position;cout << "Please enter a new character to insert into the List: " << flush;cin >> x;err = test_list.insert(position, x);if (err == overflow)cout << "List is full." << endl;if (err == range_err)cout << "Position is not valid." << endl;break;

Page 17: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

List Driver Programcase 'd': cout << "Please enter a position to delete: " << flush;

cin >> position;err = test_list.remove(position, x);if (err == range_err)

cout << "Position is not valid." << endl;else

cout << "The removed entry was " << x << "." << endl;break;

case 'r': cout << "Please enter a position to replace: " << flush;

cin >> position;cout << "Please enter a new character to put in this position:

" << flush;cin >> x;err = test_list.replace(position, x);if (err == range_err)

cout << "Position is not valid." << endl;break;

Page 18: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

List Driver Programcase 'g': cout << "Please enter a position to get: " << flush;

cin >> position;err = test_list.retrieve(position, x);if (err == range_err)

cout << "Position is not valid." << endl;else

cout << "The entry is " << x << "." << endl;break;

case 'p':test_list.traverse(print);cout << endl;break;

case 'h':help();break;

case 'q':cout << "List demonstration finished." << endl;continue_input = false;break;

}return continue_input;

}

Page 19: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

List Driver Programvoid print(List_entry &x){

cout << x << " ";}

• Note: this function is only used as a parameter for traverse.

Page 20: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Homework – Section 6.2 (page 231)

• Group Project– E1, P1 (email code) (15 pts)

Page 21: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Simply Linked Lists

The second option for our list class is the simply linked list.• Similar to a stack or queue.

• We could maintain a pointer to the current location.

Page 22: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Nodes

• We modify the node class to add templates.template <class Node_entry>struct Node{// data members

Node_entry entry;Node<Node_entry> *next;

// constructorsNode();/* Post: an empty node is created that has no next or previous nodes. */

Node(Node_entry item, Node<Node_entry> *link = NULL);/* Post: a node is created that contains the entry item and has the node link as the next

node. */};

template <class Node_entry>Node<Node_entry>::Node()/* Post: an empty node is created that has no next node. */{

next = NULL;}

template <class Node_entry>Node<Node_entry>::Node(Node_entry item, Node<Node_entry> *link)/* Post: a node is created that contains the entry item and has the node link as the next node. */{

entry = item;next = link;

}

Page 23: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Simply Linked List Class

• In the simply linked class definition all the public methods are the same.– These classes are functional replacements for each other.– Only the protected data changes.– In this implementation there is also a protected helper function.

protected:int count;mutable int current_position;Node <List_entry> *head;mutable Node <List_entry> *current;void set_position(int position) const;/* Pre: Position is a valid position in the List: 0 <=

position < count. Post: The current Node pointer references the Node

at position. */

Page 24: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Mutable Keyword

• Notice that current_position and current are mutable.

• This means that these variables can be changed by constant functions.– This makes sense; changing these really

doesn’t change the list.– We may want to change these in some of our

constant functions like retrieve.

Page 25: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Simply Linked List Methodstemplate <class List_entry>Error_code List<List_entry>::insert(int position, const List_entry &x)/* Post: If the List is not full and 0 <= position <= count the function succeeds.

Any entry formerly at position and all later entries have their position increased by 1 and x is inserted at position of the List. Else: the function fails with a diagnostic error code. */

{if (position < 0 || position > count)

return range_err;Node <List_entry> *new_node, *previous, *following;if (position > 0) {

set_position(position - 1);previous = current;following = previous->next;

}else following = head;new_node = new Node<List_entry>(x, following);if (new_node == NULL)

return overflow;if (position == 0) {

head = new_node;current_position = 0;current = head;

}else

previous->next = new_node;count++;return success;

}

Page 26: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Simply Linked List Methodstemplate <class List_entry>Error_code List<List_entry>::retrieve(int position, List_entry &x) const/* Post: The entry at the indicated position has been retrieved to the

output parameter x. If position is out of bounds an Error_code of range_err is returned. */

{if (position < 0 || position >= count || empty()) return range_err;set_position(position);x = current->entry;return success;

}

template <class List_entry>bool List<List_entry>::empty() const/* Post: If the List is empty, true is returned. Otherwise false is returned. */{

return (count == 0);}

template <class List_entry>int List<List_entry>::size() const/* Post: Return the size of the List. */{

return count;}

Page 27: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Simply Linked List Methodstemplate <class List_entry>List<List_entry>::List() // Constructor/* Post: The List is initialized to be empty.*/{

head = NULL;count = 0;

}template <class List_entry>List<List_entry>::~List() // Destructor/* Post: The List has been destroyed and its memory freed. */{

clear();}template <class List_entry>List<List_entry>::List(const List<List_entry> &original) // copy constructor/* Post: The List is initialized as a copy of List original. */{

List_entry x;count = 0;head = NULL;for (int i = 0; i < original.count; i++){

original.retrieve(i, x);insert(i, x);

}}

Page 28: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Simply Linked List Methodstemplate <class List_entry>void List<List_entry>::set_position(int position) const/* Pre: Position is a valid position in the List: 0 <= position < count. Post: The current Node pointer references the Node at position. */{

if (position < current_position){ // must start over at head of listcurrent_position = 0;current = head;

}for (; current_position != position; current_position++)

current = current->next;}

• The same driver is used for all three implementations of the list package.

Page 29: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Homework – Section 6.2 (page 231)

• Group Project– E3 (c, e, i, l), E4, P3(b) (email code) (20 pts)

Page 30: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

The Problem Simply Linked Lists

There is a problem with our simply linked list package.

• Suppose we want to delete the current entry “C”.– We need to make the pointer from “B” go to “D”.– The only way to get to “B” is to start at the head and work

through the list until we find it.– Look at the code for set_position.– To go earlier in the list than the current position it is necessary

to start over at the head.

• It would be nice if we could go backward from “C” to “B”.

Page 31: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Doubly Linked Lists

• Our third implementation is a doubly linked list.

• We can store an additional pointer in each node that goes backward in the list.

Page 32: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Removing an Entry

• Removing an entry will be fast.– No need to search from the beginning.

• Removing an entry will be more complicated.– More pointers to reroute.– Using a temporary pointer to keep track of the node

to be deleted would be a good idea.

Page 33: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Inserting an Entry

• Inserting an entry is similar.

Page 34: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Doubly Linked Nodestemplate <class Node_entry>struct Node{// data members

Node_entry entry;Node<Node_entry> *next;Node<Node_entry> *back;

// constructorsNode();/* Post: an empty node is created that has no next or previous nodes. */

Node(Node_entry item, Node<Node_entry> *link_back = NULL, Node<Node_entry> *link_next = NULL);/* Post: a node is created that contains the entry item and has the node

at link_back as the back node and link_next as the next

node. */};

Page 35: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Doubly Linked Nodestemplate <class Node_entry>Node<Node_entry>::Node()/* Post: an empty node is created that has no next node. */{

next = NULL;back = NULL;

}

template <class Node_entry>Node<Node_entry>::Node(Node_entry item, Node<Node_entry> *link_back, Node<Node_entry> *link_next)/* Post: a node is created that contains the entry item and has the node at

link_back as the back node and link_next as the next node. */{

entry = item;next = link_next;back = link_back;

}

Page 36: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Doubly Linked List Class

• Again, all the public methods have the same signatures.

• The protected data is somewhat different.– There is no need to remember the location of the head

of the list.– We can do everything using the current pointer.

protected:int count;mutable int current_position;mutable Node <List_entry> *current;void set_position(int position) const;/* Pre: Position is a valid position in the List: 0 <= position

<count.

Post: The current Node pointer references the Node at position. */

Page 37: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Doubly Linked List Methodstemplate <class List_entry>Error_code List<List_entry>::insert(int position, const List_entry &x)/* Post: If the List is not full and 0 <= position <= count the function succeeds.

Any entry formerly at position and all later entries have their position

increased by 1 and x is inserted at position of the List. Else: the function fails with a diagnostic error code. */

{Node<List_entry> *new_node, *following, *preceding;if (position < 0 || position > count) return range_err;if (position == 0) {

if (count == 0) following = NULL;else {

set_position(0);following = current;

}preceding = NULL;

}else {

set_position(position - 1);preceding = current;following = preceding->next;

}

Page 38: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Doubly Linked List Methodsnew_node = new(nothrow) Node<List_entry>(x, preceding, following);if (new_node == NULL) return overflow;if (preceding != NULL) preceding->next = new_node;if (following != NULL) following->back = new_node;current = new_node;current_position = position;count++;return success;

}

Page 39: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Doubly Linked List Methodstemplate <class List_entry>List<List_entry>::List() // Constructor/* Post: The List is initialized to be empty.*/{

count = 0;}

template <class List_entry>List<List_entry>::List(const List<List_entry> &original) // copy constructor/* Post: The List is initialized as a copy of List original. */{

List_entry x;count = 0;current = NULL;for (int i = 0; i < original.count; i++){

original.retrieve(i, x);insert(i, x);

}}

Page 40: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Doubly Linked List Methodstemplate <class List_entry>void List<List_entry>::set_position(int position) const/* Pre: Position is a valid position in the List: 0 <= position < count. Post: The current Node pointer references the Node at position. */{

if (current_position <= position)for (; current_position != position; current_position++)

current = current->next;else for(; current_position != position; current_position--)

current = current->back;}

• Several methods do not change between implementations and are not listed here.– The destructor– retrieve– empty– size

Page 41: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Homework – Section 6.2 (page 231)

• Group Project– E5 (c, e, i, l, m), P3(c) (email code) (20 pts)

Page 42: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

String Library

• Now let’s turn to implementing strings.• What operations would we want strings to support?

– Overload assignment operator– Copy constructor– Destructor– Constructor (with and without parameters)– Overload other operators (<, >, <=, >=, ==, !=)

• We would like for the following code to work as expected.String s1(“something”);String s2;s2 = “something else”;s1 = s2;

Page 43: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

String Conversions

• It would be nice if there were conversions between C-strings and our new string type.

• Convert a C-string to a String.String s = “something”;

• Convert a String to a C-string.const char *new_string = s.c_str();• The return value from the c_str method

should be a C-string of constant characters.– This needs to be constant because it is just going to

be a pointer to the data in the string object, not a copy.

Page 44: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Other String Operations

• There are more operations that we might like for our strings.– Concatenation– Read in from input stream– Print to output stream– Read until a separator character is reached– Copy a string– Copy part of a string– Search for a substring– etc.

Page 45: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

String Classclass String {public:

String(); // constructor/* Post: The String is initialized to be empty. */

~String(); // destructor/* Post: The String is deleted and its memory freed. */

String (const String &original); // copy constructor/* Post: The String is initialized to be a copy of the String original. */

String (const char *in_string); // conversion from C-string/* Pre: The pointer in_string references a C-string.

Post: The String is initialized by the C-string in_string. */

String (list<char> &in_list); // conversion from List/* Pre: The String is initialized by the character List in_list. */

const String& operator = (const String &original);// overload assignment operator/* Post: The String is reset as a copy of the String original. */

const char *c_str() const; // conversion to C-style string/* Post: A pointer to a legal C-string object matching the String is returned. */

protected:char *entries;int length;

};

Page 46: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

More String Operators

• The remaining operators do not modify their arguments and so do not need to be methods of the class.

bool operator == (const String &first, const String &second);/* Post: Return true if the String first agrees with String second. Else: Return false. */

bool operator > (const String &first, const String &second);/* Stub */

bool operator < (const String &first, const String &second);/* Stub */

bool operator >= (const String &first, const String &second);/* Stub */

bool operator <= (const String &first, const String &second);/* Stub */

bool operator != (const String &first, const String &second);/* Stub */

Page 47: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

More String Functionsvoid strcat(String &add_to, const String &add_on);/* Post: The function concatenates String add_on onto the end of String add_to. */

String read_in(istream &input);/* Post: Return a String read (as characters terminated by a newline or an end-of-

file character) from an istream parameter. */

String read_in(istream &input, int &terminator);/* Post: Return a String read (as characters terminated by a newline or an end-of-

file character) from an istream parameter. The terminating character isrecorded as the output parameter terminator. */

void write(String &s);/* Post: The String parameter s is written to cout. */

void strcpy(String &copy, const String &original);/* Post: The function copies String original to String copy. */ /* Stub */

void strncpy(String &copy, const String &original, int n);/* Post: The function copies at most n characters from String original to String

copy. */ /* Stub */

int strstr(const String &text, const String &target);/* Post: If String target is a substring of String text, the function returns the array index of the first occurrence of string stored in target in

the string stored in text. Else: The function returns a code of -1. *//* Stub */

Page 48: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

String MethodsString::~String ()/* Post: The String is deleted and its memory freed. */{

delete []entries;}

String::String(const String &original)/* Post: The String is initialized to be a copy of the String original. */{

length = original.length;entries = new char[length + 1];strcpy(entries, original.entries);

}

String::String (const char *in_string)/* Pre: The pointer in_string references a C-string. Post: The String is initialized by the C-string in_string. */{

length = strlen(in_string);entries = new char[length + 1];strcpy (entries, in_string);

}

Page 49: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

String Methods

String::String (list<char> &in_list)/* Pre: The String is initialized by the character list in_list. */{

length = in_list.size();entries = new char[length + 1];for (int i = 0; i < length; i++){ entries[i] = in_list.front();

in_list.pop_front();}entries[length] = '\0';

}

const char* String::c_str() const/* Post: A pointer to a legal C-string object matching the String is

returned. */{

return (const char *) entries;}

Page 50: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

More String Operators

• The comparison operators can all use the c_str method and then functions contained in the cstring library to make their comparisons. – They do not need access to private data, so

they do not need to be member functions.bool operator == (const String &first, const String &second)/* Post: Return true if the String first agrees with String

second. Else: Return false. */{

return strcmp(first.c_str(), second.c_str()) == 0;}

Page 51: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

More String Functions

• The rest of the string function can use methods to do their jobs, so they do not need to be methods themselves.

void strcat(String &add_to, const String &add_on)/* Post: The function concatenates String add_on onto the end of String add_to. */{

const char *cfirst = add_to.c_str();const char *csecond = add_on.c_str();char *copy = new char[strlen(cfirst) + strlen(csecond) + 1];strcpy(copy, cfirst);strcat(copy, csecond);add_to = copy;

// This uses the C-string conversion constructor and the overlaoded = operatordelete []copy;

}

String read_in(istream &input)/* Post: Return a String read (as characters terminated by a newline or an end-of-

file character) from an istream parameter. */{

list<char> temp;int size = 0;char c;while ((c = input.peek()) != EOF && (c = input.get()) != '\n') {temp.push_back(c);size++;}String answer(temp);return answer;

}

Page 52: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

More String FunctionsString read_in(istream &input, int &terminator)/* Post: Return a String read (as characters terminated by a newline or an end-of-

file character) from an istream parameter. The terminating character is recorded as the output parameter terminator. */{

list<char> temp;int size = 0;char c;while ((c = input.peek()) != EOF && (c = input.get()) != '\n') {

temp.push_back(c);size++;

}if (c == '\n') terminator = '\n';else terminator = EOF;String answer(temp);return answer;

}

void write(String &s)/* Post: The String parameter s is written to cout. */{

cout << s.c_str() << endl;}

Page 53: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Homework – Section 6.3 (page 241)

• Programming– E1(a,d) (email code, be sure to test) (8 pts)– E2 (email code) (8 pts)– E3 (a, b, c) (email code) (10 pts)

Page 54: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Text Editor

• We can use our general list class and the string class to create a basic text editor.

• A text editor is a simple word processor.– It generally doesn’t have a lot of formatting features.– It often adds features to make programming easier.

• Highlight keywords• Catch missing brackets• etc.

• Our editor will store text as a list of lines of text (paragraph) where each line is a string.

Page 55: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class

• The editor class is actually an extension of the list class.• It adds methods:

– A new constructor – Get commands– Execute commands

• It adds private data:– Command– Input stream– Output stream

• A whole raft of helper functions are also added to operate on the list of lines.

Page 56: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor ClassEditor: public List<String> {public:

Editor(ifstream *file_in, ofstream *file_out);/* Post: Initialize the Editor members infile and outfile with the

parameters. */

bool get_command();/* Post: Sets member user_command; returns true unless the user's command

is q.

Uses: C library function tolower. */

void run_command();/* Post: The command in user_command has been performed.

Uses: Methods and auxiliary functions of the class Editor, the class String, and String processing functions. */

private:ifstream *infile;ofstream *outfile;char user_command;

Page 57: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class Helper Functions

Error_code next_line();

Error_code previous_line();

Error_code goto_line();

Error_code insert_line();

Error_code substitute_line();

Error_code change_line();

void read_file(); void write_file();

void find_string();};

Page 58: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class MethodsEditor::Editor(ifstream *file_in, ofstream *file_out)/* Post: Initialize the Editor members infile and outfile with the parameters. */{

infile = file_in;outfile = file_out;

}

bool Editor::get_command()/* Post: Sets member user_command; returns true unless the user's command is q. Uses: C library function tolower. */{

if (count > 0) // Different from version in Bookcout << current_position << ":" << current->entry.c_str() << "\n??" << flush;

elsecout << "File is empty.\n??" << flush;

cin >> user_command; // ignores white space and gets commanduser_command = tolower(user_command);while (cin.get() != '\n')

; // ignore user's enter keyif (user_command == 'q')

return false;else

return true;}

Page 59: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class Methodsvoid Editor::run_command()/* Post: The command in user_command has been performed. Uses: Methods and auxiliary functions of the class Editor, the class String,

and String processing functions. */{

String temp_string;switch (user_command){case 'b':

if (empty())cout << " Warning: Empty buffer" << endl;elsewhile (previous_line() == success);break;

case 'c':if (empty())cout << " Warning: Empty file" << endl;else if (change_line() != success)cout << "Error: Substitution failed" << endl;break;

case 'd':if (remove(current_position, temp_string) != success)cout << " Error: Deletion failed" << endl;break;

Page 60: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class Methodscase 'e':

if (empty())cout << " Warning: Empty buffer" << endl;

elsewhile (next_line() == success);

break;case 'f':

if (empty())cout << " Warning: Empty file" << endl;

elsefind_string();

break;case 'g':

if (goto_line() != success)cout << " Warning: No such line" << endl;

break;case '?':case 'h':

cout << "Valid commands are b(egin) c(hange) d(el) e(nd)" << endl << "f(ind) g(o) h(elp) i(nsert) l(ength) n(ext) p(rior)" << endl

<< "q(uit) r(ead) s(ubsitute) v(iew) w(rite)" << endl; break;case 'i':

if (insert_line() != success)cout << " Error: Insertion failed" << endl;

break;

Page 61: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class Methodscase 'e':

case 'l':cout << "There are " << size() << " lines in the file." << endl;if (!empty())

cout << "Current line length is " << strlen((current->entry).c_str()) << endl;

break;case 'n':

if (next_line() != success)cout << " Warning: At end of buffer" << endl;

break;case 'p':

if (previous_line() != success)cout << " Warning: At start of buffer" << endl;

break;case 'r':

read_file();break;

case 's':if (substitute_line() != success)

cout << " Error: Substitution failed" << endl;break;

case 'v':traverse(write);break;

Page 62: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class Methodscase 'w':

if (empty())cout << " Warning: Empty file" << endl;

elsewrite_file();

break;default:

cout << "Press h or ? for help or enter a valid command:";}

}

Error_code Editor::insert_line()/* Post: A string entered by the user is inserted as a user-selected line

number. Uses: String and Editor methods and functions. */{

int line_number;cout << " Insert what line number? " << flush;cin >> line_number;while (cin.get() != '\n');cout << " What is the new line to insert? " << flush;String to_insert = read_in(cin);return insert(line_number, to_insert);

}

Page 63: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class MethodsError_code Editor::change_line()/* Pre: The Editor is not empty. Post: If a user-specified string appears in the current line, it is

replaced by a new user-selected string. Else: an Error_code is returned.

Uses: String and Editor methods and functions. */{

Error_code result = success;cout << " What text segment do you want to replace? " << flush;String old_text = read_in(cin);cout << " What new text segment do you want to add in? " << flush;String new_text = read_in(cin);

int index = strstr(current->entry, old_text);if (index == -1) result = fail;else {

String new_line;strncpy(new_line, current->entry, index);strcat(new_line, new_text);const char *old_line = (current->entry).c_str();strcat(new_line, (String)(old_line + index +

strlen(old_text.c_str())));current->entry = new_line;

}return result;

}

Page 64: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class Methodsvoid Editor::read_file()/* Pre: Either the Editor is empty or the user authorizes the command. Post: The contents of *infile are read to the Editor. Any prior contents of the Editor are overwritten. Uses: String and Editor metohds and functions. */{

bool proceed = true;if (!empty()) {

cout << "Buffer is not empty; the read will destroy it." << endl;

cout << " OK to proceed?" << endl;if (proceed = user_says_yes()) clear();

}int line_number = 0, terminal_char;while (proceed) {

String in_string = read_in(*infile, terminal_char);if (terminal_char == EOF) {

proceed = false;if (strlen(in_string.c_str()) > 0)

insert(line_number, in_string);}else insert(line_number++, in_string);

}}

Page 65: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Editor Class Methodsvoid Editor::find_string()/* Pre: The Editor is not empty. Post: The current line is advanced until either it contains a copy of a user-

selected string or it reaches the end of the Editor. If the selected

string is found, the corresponding line is printed with the string highlighted.

Uses: String and Editor methos and functions. */{

int index, length;cout << "Enter string to search for:" << endl;String search_string = read_in(cin);length = strlen(search_string.c_str()); // Different than version in the

Bookwhile ((index = strstr(current->entry, search_string)) == -1)

if (next_line() != success) break;if (index == -1) cout << "String was not found.";else {

cout << (current->entry).c_str() << endl;for (int i = 0; i < index; i++)

cout << " ";for (int j = 0; j < length; j++) // Different than version in the

Bookcout << "^";

}cout << endl;

}

Page 66: Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different

Homework – Section 6.4 (page 250)

• Programming– P1 (email code) (15 pts)