io containers

Upload: mirza-ahad-baig

Post on 02-Jun-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 Io Containers

    1/8

    CPSC 490Input

    Input will always arrive on stdin. You may assume input is well-formed with respect to the problem specification;inappropriate input (e.g. text where a number was specified, number out of range, string too long) may be handledby crashing. Normally you want to read input a word at a time:

    C++ Java

    # i n c l u d e # i n c l u d e u s i n g n am es pa ce s t d ;. . .i nt i ; s t r in g s ; doubl e d ;c i n >> i >> s >> d ;

    / / C he ck f o r e ndof f i l ei f ( c in >> v ar ) / / r e ad OKe l s e / / EOF

    i m po r t j a v a . u t i l . ;. . .S c a n ne r s c = new S c a n ne r ( S ys te m . i n ) ;i n t i = s c . n e x t In t ( ) ;S t r i n g s = s c . n ex t ( ) ;d o u b l e d = s c . n e x tD o u bl e ( ) ;

    / / C heck f o r endof f i l ei f ( s c . h as Ne xt ( ) ) / / c an r e a de l s e / / EOF

    Occasionally you want to deal with a line at a time instead (e.g. dealing with strings that might have whitespace inthem or variable numbers of words without counts specified):

    C++ Java

    # i n c l u d e # i n c l u d e u s i n g n am es pa ce s t d ;. . .s t r i n g l i n e ;g e t l i n e ( c i n , l i n e ) ;

    i m po r t j a v a . u t i l . ;. . .S c a n ne r s c = new S c a n ne r ( S ys te m . i n ) ;S t r i n g l i n e = s c . n e xt L in e ( ) ;

    NOTE: If you use both word-based and line-based functions in the same program, if you reach the end of a line usingthe word-based functions, the line-based functions will see an empty line before the following line. Therefore, if youdo this, call the line function one extra time and discard its output. For example, given the following input file:

    17The q u i c k br own f o x j ump s o v e r t h e l a z y d og .

    the following code will parse it properly:

    C++ Java

    # i n c l u d e # i n c l u d e u s i n g n am es pa ce s t d ;

    . . .i n t n umb er ;s t r i n g s e n t en c e ;c i n >> number ;/ / D i s c ar d t h e p se ud ol i n eg e t l i n e ( c i n , s e n t e nc e ) ;// Read t h e r e a l l i n eg e t l i n e ( c i n , s e n t e nc e ) ;

    i m po r t j a v a . u t i l . ;. . .S c a n ne r s c = new S c a n ne r ( S ys te m . i n ) ;

    i n t nu mbe r = s c . n e x t I n t ( ) ;/ / D i s c ar d t h e p se ud ol i n esc . nextLi ne ( ) ;// Read t h e r e a l l i n eS t r i n g s e n t e n c e = s c . n e x tL i n e ( ) ;

    1

  • 8/10/2019 Io Containers

    2/8

    Output

    Output always goes to stdout. For most problems, the output your program generates must be exactly byte-for-byteidentical to the correct output. This means the following will result in errors:

    wrong answers

    incorrect spelling

    incorrect capitalization

    incorrect number of decimal places

    incorrect use of whitespace, including blanks at end of line

    confusing a blank line between test cases with a blank line after each test case

    The following example prints out the following (excluding the braces): {$1234 hello world 27.35}and then movesto the next line.

    C++ Java

    # i n c l u d e

    u s i n g n am es pa ce s t d ;. . .i n t d o l l a r s = 1 23 4;d ou bl e f o o = 2 7 . 3 5 ;s t r i n g word = h e l l o ;// # d ec im al p l a c e s f o r d ou b le s &// f l o a t scout

  • 8/10/2019 Io Containers

    3/8

    Containers: Lists

    A list stores a collection of items (of the same type) in an order specified as the items are added. Each item hasa position in the list, and is normally identified by its position (positions are counted starting from zero). Listsgenerally allow duplicates.If you have a reasonable upper bound on the amount of data and you dont need to store the exact size (e.g. becauseits implied by other parts of the problem), consider using a simple array declared to be the maximum size. In Java,dynamically allocating arrays with sizes not known at compile time can be useful; in C++ you have to remember to

    free such arrays manually so vectors are often a better choice.One more advanced list is the vector, which is implemented on top of an array which is reallocated as needed. Vectorsare fast for finding an element by its position and adding and removing elements at the end of the list, but slow forfinding an element by its value and adding and removing elements other than at the end of the list.

    C++ Java

    # i n c l u d e u s i n g n am es pa ce s t d ;. . .v e c t o r numbers ;numbers . push back (5 );numbers . push back (7 );

    / / I n s e r t i n t h e m i d dl e (SLOW ! ) :num bers . i n se rt (num bers . begi n () + 1 , 6) ;

    a s s e r t ( n u mb er s . s i z e ( ) == 3 ) ;a s s e r t ( n u mb er s [ 0 ] == 5 ) ;a s s e r t ( n u mb er s [ 1 ] == 6 ) ;a s s e r t ( n u mb er s [ 2 ] == 7 ) ;num bers . c l ea r ( ) ;as se rt ( num bers . empty () ) ;

    i m po r t j a v a . u t i l . ;. . .L i s t numbers =

    new ArrayLi st( ) ;numbers .add (5 );numbers .add (7 );

    / / I n s e r t i n t h e m i d dl e (SLOW ! ) :num bers . add( 1 , 6) ;

    a s s e r t ( n u mb er s . s i z e ( ) == 3 ) ;as se rt (num bers . get (0) == 5) ;as se rt (num bers . get (1) == 6) ;as se rt (num bers . get (2) == 7) ;num bers . c l ea r ( ) ;

    3

  • 8/10/2019 Io Containers

    4/8

    Another type of list is the linked list, which is implemented as a string of nodes each of which knows how to find thenode before and after itself. Linked lists are fast for inserting and removing elements anywhere (at the beginning orend or any location at which one holds an iterator) and iterating forward or backwards through all elements, butslow for finding an element by its position or value.

    C++ Java

    # i n c l u d e < l i s t >u s i n g n am es pa ce s t d ;. . .l i s t numbers ;numbers . push back (7 );num bers . pus h f ro nt (5) ;

    / / Get i t e r a t o r by p o s i t i o n (SLOW ! ) :l i s t : : i t e r a t o r i t e r

    = num bers . begi n () + 1;a s s e r t (i t e r == 7 ) ;

    // I n s e rt b e fo r e i t e r a t o r ( f a s t ) :

    n um be rs . i n s e r t ( i t e r , 6 ) ;a s s e r t ( n u mb er s . s i z e ( ) == 3 ) ;

    / / G et e l e m e n t s b y p o s i t i o n (SLOW ! ) :a s s e r t ( ( num bers . begi n () + 0) == 5) ;a s s e r t ( ( num bers . begi n () + 1) == 6) ;a s s e r t ( ( num bers . begi n () + 2) == 7) ;

    i m po r t j a v a . u t i l . ;. . .L i s t numbers =

    new L i n k e d L i s t() ;n um be rs . a dd ( 7 ) ; / / a t e ndnumbers . a dd ( 0 , 5 ) ; / / a t s t a r t

    / / Get i t e r a t o r by p o s i t i o n (SLOW ! ) :L i s t I t e r a t o r i t e r =

    numbers . l i s t I t e r a t o r ( 1 ) ;a s s e r t ( i t e r . n e x t ( ) == 7 ) ;/ / T he i t e r a t o r moved . Move i t b ac k .i t e r . p r e v i o u s ( ) ;

    // I n s e rt b e fo r e i t e r a t o r ( f a s t ) :i t e r . ad d ( 6 ) ;a s s e r t ( n u mb er s . s i z e ( ) = 3 ) ;

    / / G et e l e m e n t s b y p o s i t i o n (SLOW ! ) :as se rt (num bers . get (0) == 5) ;as se rt (num bers . get (1) == 6) ;as se rt (num bers . get (2) == 7) ;

    These are the general-purpose lists. There is also a deque, or double-ended queue, which provides slightly differentservices in C++ and in Java. In C++, deque acts very like a vector except allowing fast adding and removing of

    elements at both ends (not only the back). In Java, ArrayDeque (added in version 1.6.0) also allows adding andremoving elements at both ends, but does not allow efficiently accessing an element by its position. In this course,deques may be used in certain special cases where the front-and-back semantics are required, but we will not beaccessing elements by position.

    C++ Java

    # i n c l u d e u s i n g n am es pa ce s t d ;. . .deque numbers ;numbers . push back (7 );numbers . push back (8 );

    num bers . pus h f ro nt (6) ;num bers . pus h f ro nt (5) ;a s s e r t ( n u mb er s . s i z e ( ) == 4 ) ;f or ( i nt i = 5 ; i

  • 8/10/2019 Io Containers

    5/8

    Finally, there is the queue, which is similar to a deque but is intended for use in situations where all elements areadded at one end and removed at the otherin other words, a FIFO. In C++, queueis a class which uses a templateparameter to choose which implementation to use (typical choices arelistanddeque, withdequebeing the default).In Java, Queue is an interface implemented by both LinkedList and ArrayDeque.

    C++ Java

    # i n c l u d e u s i n g n am es pa ce s t d ;. . .queue numbers ;numbers . push ( 5 ) ;numbers . push ( 6 ) ;numbers . push ( 7 ) ;numbers . push ( 8 ) ;a s s e r t ( n u mb er s . s i z e ( ) == 4 ) ;f or ( i nt i = 5 ; i

  • 8/10/2019 Io Containers

    6/8

    Containers: Maps

    Mapsare collections of key-value pairs, optimized for looking up the value associated with a known key. There aretwo variants: hashtablesperform most operations faster (many in constant time) but do not keep their keys in sortedorder, while trees are slower (performing most operations in logarithmic time) but keep their keys sorted, whichmay be useful for iteration. Maps normally do not allow duplicate keys. In general trees are fast enough for mostpurposes, and defining hash functions in C++ is somewhat nonintuitive. Therefore, we will use trees in this class:

    C++ Java

    # i n c l u d e u s i n g n am es pa ce s t d ;. . .

    map days ;

    // Add el em ent s :d ay s [ Monday ] = 1 ;d ay s [ T uesday ] = 2 ;days [ Wednesday ] = 3;d ay s [ T hu rs da y ] = 4 ;d ay s [ F ri da y ] = 5 ;d a ys [ S a t ur d a y ] = 6 ;days [ Sunday ] = 7 ;

    / / C he ck p r e s e n c e :as se rt ( days . count( Monday) == 1) ;as se r t ( days . count (NotADay) == 0) ;

    / / Get v a l u e s :a s s e r t ( d a ys [ M onday ] == 1 ) ;a s s e r t ( d a ys [ T ue sd ay ] == 2 ) ;

    // I t e ra t e key s i n o rd er o f

    : : i t e r a t o r i , i en d ;f o r ( i = d a ys . b e g i n ( ) ,i e n d = d a ys . e nd ( ) ; i ! = i e n d ; ++i ) {

    s t r i n g key = i>f i r s t ;i n t v al ue = i>secon d ;

    }

    / / E r as e by k ey .days . era se (Tuesday ) ;

    i m po r t j a v a . u t i l . ;. . .

    Map d a y s =new TreeMap( ) ;

    // Add el em ent s :d ay s . p ut ( Monday , 1 ) ;d ay s . p ut ( T uesd ay , 2 ) ;days . put( Wednesday , 3) ;d ay s . p ut ( T h ur sd ay , 4 ) ;days . put ( Fr id ay , 5 ) ;d ay s . p ut ( S a tu r da y , 6 ) ;d ay s . p ut ( Sunday , 7 ) ;

    / / C he ck p r e s e n c e :as se rt (days . contai nsK ey (Monday )) ;as se rt ( ! days . contai nsK ey( NotADay ) );

    / / Get v a l u e s :as se rt ( days . get (Monday) == 1) ;as se rt ( days . get (Tuesday) == 2) ;

    / / I t e r a t e k ey s i n o r d er o f C omp ar ab le :

    fo r (Map. Entry

    i: d a ys . e n t r y S e t ( ) ) {S t r i n g k ey = i . g et Ke y ( ) ;i n t v a l u e = i . g e t Va l ue ( ) ;

    }

    / / E r as e by k ey .days . remove( Tuesday );

    6

  • 8/10/2019 Io Containers

    7/8

    Containers: Sets

    A set is a map without values: its only purpose is to contain values (not allowing duplicates) and permit efficientchecking of whether or not a value is contained in the set. As with maps, typical implementations are hashtable-basedor tree-based. Again, hashtables keep their values unordered but are faster, while tree-based sets keep their valuesin their natural order, and we will use tree sets in most cases for this class to avoid defining hash functions.

    C++ Java

    # i n c l u d e u s i n g n am es pa ce s t d ;. . .s e t words ;

    // Add el em ent s :w or ds . i n s e r t ( F oo ) ;w or ds . i n s e r t ( B ar ) ;w or ds . i n s e r t ( B az ) ;

    / / C he ck p r e s e n c e :a s s e r t ( w o r ds . c o u nt ( F oo ) == 1 ) ;as se rt (words . count(Q uux) == 0) ;

    // I t e r a t e e le me nt s i n o rd er o f

  • 8/10/2019 Io Containers

    8/8

    Sorting: Natural and Custom Orders

    Every data type can have a natural ordering, which is used to determine in which order objects of that type shouldbe sorted. Data types can also have any number ofcustom orderings, which can be explicitly used to sort objects ina different order. Functions are available in the standard libraries to efficiently sort arrays and vectors (quicksort).

    C++ Java

    # i n c l u d e # i n c l u d e # i n c l u d e # i n c l u d e # i n c l u d e u s i n g n am es pa ce s t d ;. . .

    / / D e f i n e a c us to m t y pe :c l a s s my ty pe {

    p u b l i c :i n t f o o ;s t r i n g b ar ;

    } ;

    / / N a t ur a l o r d e r i n g :// R et urn s t ru e i f x < y ,// f a l s e i f x >= y .b o o l o p e r a to r 0 f o r >,// 0 f o r = ,