1 / 40

Main Index

CSE 331 - Lecture 9. 1. Main Index. Contents. Chapter 6 Shifting blocks of elements… Model of a list object… Sample list The list ADT CLASS list Constructors CLASS list Operations CLASS list::iterator Operations Inserting an element into a list Removing an element from a list

rollo
Download Presentation

Main Index

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. CSE 331 - Lecture 9 1 Main Index Contents • Chapter 6 • Shifting blocks of elements… • Model of a list object… • Sample list • The list ADT • CLASS list Constructors • CLASS list Operations • CLASS list::iterator Operations • Inserting an element into a list • Removing an element from a list • Ordered lists • Splicing two lists • Summary Slides • NCurses (curses.h) • Background • Curses “Hello World” • Initializing & Shutting down • Moving cursor • I/O (printw, scanw & getch) • Color • Using Special keys (F1, …) • Using the Mouse • Examples • hi.cpp • mvbox.cpp • mvboxM.cpp • tttCM.cpp

  2. Curses Library • Allows “text-based” GUI • Curses or Ncurses for Unix/Linux/AIX • PDCurses (Public Domain Curses) for Dos/Windows • Supports mouse, keypads, color, buffered & non-buffered input, and some simple graphics (lines, boxes, etc)

  3. Curses (Windows, etc) • Curses works by creating a window / screen / console data structure within which the program moves the cursor and performs output • A refresh() function updates the actual window / screen / console to reflect the logical one • See class web site for URLs of Curses resources / tutotrials / examples/ etc.

  4. Curses Basics #include<curses.h> int main() { // always do this first initscr(); // initialize curses // these are optional cbreak(); // input keys immediately available noecho(); // stop echoing inputs nonl(); // faster cursor movement // move cursor to location and output message // upper left screen corner is 0,0 move(12,5); // move cursor to row 12, column 5 printw(“Hello World\n”); // instead of cout << ... refresh(); // make it visible to us getch(); // wait for a key to be hit endwin(); // release window back to shell return 0; }

  5. CursesInitialization & Shutdown • Must use • initscr(); // called first to initialize curses • endwin(); // called last to return screen to normal • Probably use • cbreak(); // enable direct keystroke access • noecho(); // prevent echoing of input • nonl(); // speeds cursor movement • getmaxyx(stdscr,h,w); // get screen limits • Notes: • stdscr is the default screen/window

  6. CursesMoving cursor & I/O • Cursor & position • move(y,x); // move cursor to line y, char posit x • Upper left of screen is at position 0,0 • getyx(y,x); // returns current cursor location • I/O • printw(“%d %s”, num, str); // cout << • Parameters are same as printf() • Prints in window from current cursor location • scanw(“%f”,&realNum); // cin >> • Parameters are same as scanf() • Reads input stream as directed by format string • getch(); // reads single keystroke • wgetch(stdscr); // reads single keystroke • From indicated window

  7. CursesMoving cursor & I/O • Combined movement and I/O • mvprintw(y,x,“%d %s”, num, str); • Prints in window from cursor location y, x • mvscanw(y,x,“%f”,&realNum); • Reads input stream as directed by format string • Making it visible • refresh(); // updates console • Makes it match logical window data structure

  8. Curses Color • Only supported on certain terminal types • xterm is good bet • set term=xterm • at unix prompt before running program • start_color(); // initializes color • init_pair(num,fg_color,bg_color); • Creates a COLOR_PAIR of foreground and background colors • xterm has 8 colors and 64 color pairs, max • attron(COLOR_PAIR(num)); • // makes color pair the output attribute until turned off • attroff(COLOR_PAIR(num));

  9. Curses COLORS • COLOR_BLACK • COLOR_RED • COLOR_GREEN • COLOR_YELLOW • COLOR_BLUE • COLOR_MAGENTA • COLOR_CYAN • COLOR_WHITE

  10. Curses Using Special Keys • To use function keys, arrows, etc. Initialize with • keypad(stdscr,TRUE); • Must be used before both special key input • And before mouse event capture • prevents immediate translation to ASCII • Get key with • int key = getch(); • Test key with keycodes • KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT • KEY_HOME, KEY_BACKSPACE • KEY_F(n) Function keys, for 0 <= n >= 63 • KEY_DC Delete character • KEY_IC Insert char or enter insert mode • KEY_ENTER Enter or send

  11. Curses Mouse Support • Only in Ncurses (Linux & AIX) • Initialize for capture of events with • mousemask(ALL_MOUSE_EVENTS,NULL); • Specific masks (BUTTON1_CLICKED, ...) • Read mouse click with • int key = getch(); or • int key =wgetch(stdscr);

  12. Curses Mouse Events • Processing event • Value read will equal KEY_MOUSE • Use getmouse(&event) to recover event from event queue • Use event.bstate to determine button state (which event) • Use event.x and event.y to determine where mouse was clicked in window MEVENT event; // data type for mouse event if (key == KEY_MOUSE) // if it was the mouse if (getmouse(&event) == OK) { // get the event if (event.bstate & BUTTON1_CLICKED) { // so do something with // event.y; and event.x;

  13. Example Curses Programs • Source Code is on Class Web Site • Hi • Simple curses “Hello World” program • Mvbox • Moving star shape • Uses keyboard (letter) inputs • mvboxM • Moving star shape • Uses keyboard, special keys, and mouse input • tttCM • TicTacToe • Uses Color, mouse and keyboard inputs

  14. Shifting blocks of elements to insert or delete a vector item

  15. 15 Main Index Contents Model of a list object with links to next and previous element

  16. 16 Main Index Contents The List ADT • The list API documents the member function prototype as well as pre- and postconditions. • provides three constructors to declare a list object.

  17. list(); Create an empty list. This is the default constructor. CLASS list <list> Constructors list(int n, const T&value = T()); Create a list with n elements, each having a specified value. If the value argument is omitted, the elements are filled with the default value for type T. Type T must have a default constructor, and the default value of type T is specified by the notation T(). list(T *first, T *last); Initialize the list, using the address range [first, last). 17 Main Index Contents

  18. T& back(); Return the value of the item at the rear of the list. Precondition: The vector must contain at least one element. CLASS list <list> Operations bool empty() const; Return true if the vector is empty, false otherwise. T& front(); Return the value of the item at the front of the list. Precondition: The vector must contain at least one element. 18 Main Index Contents

  19. void push_back(const T& value); Add a value at the rear of the list. Postcondition: The list has a new element at the rear, and its size increases by 1. CLASS list <list> Operations void pop_back(); Remove the item at the rear of the list. Precondition: The list is not empty. Postcondition: The list has a new element at the rear or is empty. 19 Main Index Contents

  20. void push_front(const T& value); Add a value at the front of the list. Postcondition: The list has a new element at the front, and its size increases by 1. CLASS list <list> Operations void pop_front(); Remove the item at the front of the list. Precondition: The list is not empty. Postcondition: The list has a new element at the front or is empty. int size() const; Return the number of elements in the vector. 20 Main Index Contents

  21. iterator begin(); Returns an iterator that references the first position (front) of the list. If the list is empty, the iterator value end() is returned. CLASS list <list> Operations const_iterator begin(); Returns a const_iterator that points to the first position (front) of a constant list. If the list is empty, the const_iterator value end() is returned. iterator end(); Returns an iterator that signifies a location immediately out of the range of actual elements. A program must not dereference the value of end() with the * operator. 21 Main Index Contents

  22. iterator end(); Returns an iterator that signifies a location immediately out of the range of actual elements. A program must not dereference the value of end() with the * operator. CLASS list <list> Operations const_iterator end(); Returns a const_iterator that signifies a location immediately out of the range of actual elements in a constant list. A program must not dereference the value of end() with the * operator. 22 Main Index Contents

  23. void erase(iterator pos); Erase the element pointed to by pos. Precondition: The list is not empty. Postcondition: The list has one fewer element. CLASS list <list> Operations void erase(iterator first, iterator last); Erase all list elements within the iterator range [first, last]. Precondition: The list is not empty. Postcondition: The size of the list decreases by the number of elements in the range. 23 Main Index Contents

  24. CLASS list <list> Operations 24 Main Index Contents iterator insert(iterator pos, const T& value); Insert value before pos, and return an iterator pointing to the position of the new value in the list. The operation does not affect any existing iterators. Postcondition: The list has a new element.

  25. *: Accesses the value of the item currently pointed to by the iterator. *iter; CLASS list::iterator <list> Operations ++: Moves the iterator to the next item in the list. iter++; --: Moves the iterator to the previous item in the list. iter--; ==: Takes two iterators as operands and returns true when they both point at the same item in the list. iter1 == iter2 !=: Returns true when the two iterators do not point at the same item in the list. iter1 != iter2 25 Main Index Contents

  26. Palindromes • Strings that read the same forwards and backwards • Spaces and punctuation are ignored • Approaches (using lists) • 1 – Pop matching pairs of 1st & last chars • 2 – Scan inward to middle, matching corresponding outermost pairs

  27. Palindrome (pop matches) // Assume spaces & punctuation removed // by caller; all letters in lower case template<typename T> bool isPal_1(const list<T>& alist) { list<T> copyList; copyList = alist; while (copyList.size() > 0) { if (copyList.front() != copyList.back()) return false; // mismatch, not a palindrome // pop matching pair copyList.pop_front(); copyList.pop_back(); } return true; // all pairs matched & popped }

  28. Palindrome (scan inward) // Assume spaces & punctuation removed // by caller; all letters in lower case template<typename T> bool isPal_2(const list<T>& alist) { list<T>::iterator left, right; left = alist.begin(); right = alist.end(); right--; while (left != right) { if (*left != *right) return false; // mismatch, not a palindrome right--; // move right iter 1 posit left if (left == right) return true; // even length string, we’re done left++; // move left 1 posit right } return true; // all pairs matched & popped }

  29. SeqSearch // search values [*first,*last)- sequentially template<typename T> List<T>::iterator seqSearch ( list<T>::iterator& first, list<T>::iterator& last, const T& target) { list<T>::iterator iter = first; while((iter != last) && (*iter != target)) iter++; return iter; }

  30. 30 Main Index Contents Inserting an element into a list

  31. Removing an element from a list

  32. 32 Main Index Contents Splicing two lists

  33. Ordered Lists • Values maintained in order by key • Numerical • Alphabetical • Lexicographical • Insertion is two step process • Search for first list value (V) equal to or greater than new value • Insertion of new value in front of list value (V) • Examples • Inserting • Removing duplicates • Merging lists

  34. Inserting in Ordered List template<typename T> void insertOrder (list<T>& orderedList, const T& item) { list<T>::iterator curr = orderedList.begin(), stop = orderedList.end(); // find insertion spot, 1st value >= item while((curr != stop) && (*curr < item)) curr++; // insert item ahead of *curr orderedList.insert(curr, item); }

  35. Removing Duplicates // assume list is ordered. This way we can jump curr // ahead as soon as we find *p != *curr template<typename T> void removeDups (list<T>& orderedList) { list<T>::iterator curr, p; curr = orderedList.begin(); while (curr != orderedList.end()) { p = curr; p++; while ((p != orderedList.end() && (*p == *curr)) // pass p, move p forward, and call erase orderedList.erase(p++); curr = p; } }

  36. 36 Main Index Contents Summary Slide 1 §- list - A Sequence of elements stored by position. - Index access is not available… §- to access the value of an element, must pass through its preceding elements. §-list iterator - A generalized pointer that moves through a list element by element… forward or backward - At any point, the * operator accesses the value of a list item.

  37. 37 Main Index Contents Summary Slide 2 §- The list class has two iterator types: 1) iterator: A generalized list traversal pointer. 2) const_iterator: must be used with a constant list object. Each type is a nested class of list and must be accessed by using the scope operator ::

  38. 38 Main Index Contents Summary Slide 3 §- the list member function begin() - Gives an iterator an initial value that points to the first element. §- the list member function end() - Returns an iterator pointing just past the last element of the list.

  39. 39 Main Index Contents Summary Slide 4 §- The sequential search of a list object - implemented by using an iterator range [first, last). - It returns an iterator that points at the target value or has value last if the target is not in the list.

  40. 40 Main Index Contents Summary Slide 5 • §- list class member fns insert() and erase() • - Both use an iterator argument to modify a list. • insert(pos): places value in the list before the data referenced by the iterator pos. • erase(pos): removes the data item referenced by pos from the list.

More Related