main index contents 11 main index contents ncurses (curses.h) background curses “hello world”...
Post on 21-Dec-2015
220 views
TRANSCRIPT
1 Main IndexMain Index ContentsContents1 Main IndexMain Index ContentsContents
NCurses (curses.h)NCurses (curses.h)
BackgroundBackgroundCurses “Hello World”Curses “Hello World”Initializing & Shutting downInitializing & Shutting downMoving cursorMoving cursorI/O (printw, scanw & getch)I/O (printw, scanw & getch)ColorColorUsing Special keys (F1, …)Using Special keys (F1, …)Using the MouseUsing the MouseExamples Examples
hi.cpphi.cppmvbox.cppmvbox.cppmvboxM.cppmvboxM.cpptttCM.cpptttCM.cpp
CSE 331 - Lecture 9CSE 331 - Lecture 9Chapter 6Chapter 6
Shifting blocks of elements…Shifting blocks of elements…Model of a list object…Model of a list object…Sample listSample listThe list ADTThe list ADTCLASS list ConstructorsCLASS list ConstructorsCLASS list OperationsCLASS list OperationsCLASS list::iterator CLASS list::iterator OperationsOperationsInserting an element into a listInserting an element into a listRemoving an element from a Removing an element from a listlistOrdered listsOrdered listsSplicing two listsSplicing two listsSummary SlidesSummary Slides
2 Main IndexMain Index ContentsContents
Curses LibraryCurses 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 Main IndexMain Index ContentsContents
Curses (Windows, etc)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 Main IndexMain Index ContentsContents
Curses BasicsCurses 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 Main IndexMain Index ContentsContents
CursesCursesInitialization & ShutdownInitialization & 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 Main IndexMain Index ContentsContents
CursesCursesMoving cursor & I/OMoving 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 Main IndexMain Index ContentsContents
CursesCursesMoving cursor & I/OMoving 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 Main IndexMain Index ContentsContents
Curses ColorCurses 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 Main IndexMain Index ContentsContents
Curses COLORSCurses COLORS COLOR_BLACK COLOR_RED COLOR_GREEN COLOR_YELLOW COLOR_BLUE COLOR_MAGENTA COLOR_CYAN COLOR_WHITE
10 Main IndexMain Index ContentsContents
Curses Curses Using Special KeysUsing 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 Main IndexMain Index ContentsContents
Curses Mouse SupportCurses 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 Main IndexMain Index ContentsContents
Curses Mouse Events 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 Main IndexMain Index ContentsContents
Example Curses ProgramsExample 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 Main IndexMain Index ContentsContents
Shifting blocks of elements to Shifting blocks of elements to insert or delete a vector iteminsert or delete a vector item
15 20 30 35 40Initial V ec to r
30 3515 40
20
Eras e 20 atP o s itio n 1
S hift left0 4321
15 20 30 35 4025Ins ert 25 at
P o s itio n 2
S hift right
32
10 54
15 20 30 35 40Initial V ec to r
0 4321 210 3
15 Main IndexMain Index ContentsContents15 Main IndexMain Index ContentsContents
Model of a list object with links Model of a list object with links to next and previous elementto next and previous element
fro nt b ac k
16 Main IndexMain Index ContentsContents16 Main IndexMain Index ContentsContents
The List ADTThe List ADT The list API documents the member function
prototype as well as pre- and postconditions.– provides three constructors to declare a list object.
0 .00 .0 0 .00 .0 0 .00 .0 0 .00 .0(a) lis t< d o ub le> realL is t(8)
8 :3 08 :3 0 8 :3 08 :3 0 8 :3 0 8 :3 0(b ) lis t< tim e24> tim eLis t(6, 8:30)
ar ray
(c ) lis t< s tring> s trL is t(s trA rr, s trA rr+ 3)l is tve c to r
17 Main IndexMain Index ContentsContents17 Main IndexMain Index ContentsContents
CLASS list Constructors <list>
list();Create an empty list. This is the default constructor.
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).
18 Main IndexMain Index ContentsContents18 Main IndexMain Index ContentsContents
CLASS list Operations <list>
T& back();Return the value of the item at the rear of the list. Precondition: The vector must contain at least one
element.
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.
19 Main IndexMain Index ContentsContents19 Main IndexMain Index ContentsContents
CLASS list Operations <list>
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.
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.
20 Main IndexMain Index ContentsContents20 Main IndexMain Index ContentsContents
CLASS list Operations <list>
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.
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.
21 Main IndexMain Index ContentsContents21 Main IndexMain Index ContentsContents
CLASS list Operations <list>
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.
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.
22 Main IndexMain Index ContentsContents22 Main IndexMain Index ContentsContents
CLASS list Operations <list>
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.
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.
23 Main IndexMain Index ContentsContents23 Main IndexMain Index ContentsContents
CLASS list Operations <list>
void erase(iterator pos);Erase the element pointed to by pos.Precondition: The list is not empty.Postcondition: The list has one fewer element.
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.
24 Main IndexMain Index ContentsContents24 Main IndexMain Index ContentsContents
CLASS list Operations <list>
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 Main IndexMain Index ContentsContents25 Main IndexMain Index ContentsContents
CLASS list::iterator Operations <list>
*:Accesses the value of the item currently pointed to by the iterator.
*iter;*iter;
++: Moves the iterator to the next item in the list. iter++;iter++;
--: Moves the iterator to the previous item in the list.
iter--;iter--;
==: Takes two iterators as operands and returns true when they both point at the same item in the list.
iter1 == iter2iter1 == iter2
!=: Returns true when the two iterators do not point at the same item in the list.
iter1 != iter2iter1 != iter2
26 Main IndexMain Index ContentsContents
PalindromesPalindromes 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 Main IndexMain Index ContentsContents
Palindrome (pop matches)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 Main IndexMain Index ContentsContents
Palindrome (scan inward)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 Main IndexMain Index ContentsContents
SeqSearchSeqSearch// 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 Main IndexMain Index ContentsContents30 Main IndexMain Index ContentsContents
Inserting an element into a listInserting an element into a list
fro nt
Lis t o b je c t (a fte r)
fro nt re a r
Lis t o b je c t (b e fo re )
ne w E ltre a r
ite r
2 55937 2 9374
ite r4
31 Main IndexMain Index ContentsContents
Removing an element from a listRemoving an element from a list
fro nt
Lis t o b je c t (a fte r)
fro nt re a r
Lis t o b je c t (b e fo re )
re a rite r
2 5937 2 593
ite r? ?
32 Main IndexMain Index ContentsContents32 Main IndexMain Index ContentsContents
Splicing two listsSplicing two lists
7 1 5 1 6 3 47 1 5 3 47 3 4
d e s tLis t
1 5 1 6
s o u rc e Ite r
s o u rc e Lis t p o s
5
d e s tLis t (A fte r ins e rt o f 1 5 )
1 5 1 6
s o u rc e Ite r
s o u rc e Lis t p o s
5
d e s tLis t (A fte r ins e rt o f 1 6 )
1 5 1 6
s o u rc e Ite r
s o u rc e Lis t p o s
5
33 Main IndexMain Index ContentsContents
Ordered ListsOrdered 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 Main IndexMain Index ContentsContents
Inserting in Ordered ListInserting in Ordered Listtemplate<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 Main IndexMain Index ContentsContents
Removing DuplicatesRemoving Duplicates// assume list is ordered. This way we can jump curr// ahead as soon as we find *p != *currtemplate<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 Main IndexMain Index ContentsContents36 Main IndexMain Index ContentsContents
Summary Slide 1Summary 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 Main IndexMain Index ContentsContents37 Main IndexMain Index ContentsContents
Summary Slide 2Summary Slide 2
§- The list class has two iterator types:1)1) iteratoriterator:
A generalized list traversal pointer.
2)2) constconst __ iteratoriterator:
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 Main IndexMain Index ContentsContents38 Main IndexMain Index ContentsContents
Summary Slide 3Summary 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 Main IndexMain Index ContentsContents39 Main IndexMain Index ContentsContents
Summary Slide 4Summary Slide 4
§- The sequential search of a list object- implemented by using an iterator range
[firstfirst, lastlast).
- It returns an iterator that points at the target value or has value lastlast if the target is not in the list.
40 Main IndexMain Index ContentsContents40 Main IndexMain Index ContentsContents
Summary Slide 5Summary Slide 5
§- list class member fns insert() and erase()
- Both use an iterator argument to modify a list.
1)1) insert(pos)insert(pos): places value in the list before the data
referenced by the iterator pospos.
2)2) erase(pos)erase(pos):removes the data item referenced by pospos from the list.