DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
No More String Errors - String(3C++)

Queue-Oriented Operations

This group of functions treats a String as a queue. The primary operators are put and getX, which correspond to << and >> on iostreams and unputX and unget, which make it possible to use a String as a stack or deque Figure 1 shows the relationships of the queue-oriented functions. They allow new characters to be added or removed at either end of the String. put and unget, the operators that add characters to the String, can also take String arguments, so they serve as append and prepend operators (respectively) as well.

Queue-oriented functions


put
String& String::put(char);

s.put(c) puts character c on the end of String s, s.put(t) appends String t to String s and s.put(p) appends the characters pointed to by character pointer p to s. put returns its updated object, so s.put('y').put('z') will append "yz" to String s. The meaning of s.put(t) is the same as s += t.


getX
int String::getX(char&);

If String s is non-empty, s.getX(c) gets (and removes) the first character from s, assigns it to c, and returns 1. Otherwise, s and c are unchanged, and the return value is 0.


unget
String& String::unget(char);

s.unget(c) undoes the effect of s.getX(c) (which removes the first character from s); that is, it puts c back on the front (got that?) of s. In another sense, unget is the reverse of put since it prepends rather than appends to its object. The type rules are exactly the same as for put. unget returns its object.


unputX
int String::unputX(char&);

s.unputX(c) undoes the effect of s.put(c) (which appends c to s); that is, it gets (and removes) the last character from String s, and assigns it to c. Similarly, in another sense, unputX is the reverse of getX since it removes the last (instead of the first) character of its String.

Both getX() and unputX() have variants that do not take an argument but otherwise have the same effect: to remove an element from the queue and return 1, if the queue was non- empty, and to return 0 otherwise. Since they don't assign to their argument, they don't have the final ``X'' and are called get() and unput().

The remove function at the beginning of the paper is an example of the use of getX. A stack can be easily constructed using put and unputX:

   class char_stack : private String {
   public:
               char_stack()   {}
               ~char_stack()  {}
               empty()        { return is_empty(); }
       char    pop()          { char x; if (!unputX(x))
                                            error();
                                        return x; }
       void    push(char x)   { put(x); }
   }

Notice that unget and getX could have been used instead of put and unputX.


Next topic: Input and Output
Previous topic: Basic Operations

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004