main (int argc, char *argv[])
{
if (argc!= 3) error("two arguments expected");
int count = 0;
int m = atoi(argv[1]);
int n = atoi (argv[2]);
intset s(m,n);
int t = 0;
while (count ‹m) {
t = randint(n);
if (s.member(t)==0) {
s.insert(t);
count++;
}
}
print_in_order(&s);
}
b5_4_5.cxx
#include ‹stream.hxx›
struct cl
{
char* val;
void print(int x) { cout ‹‹ val ‹‹ x ‹‹ "\n"; }
cl(char *v) { val = v; }
};
typedef void (cl::*PROC)(int);
main()
{
cl z1("z1 ");
cl z2("z2 ");
PROC pf1 = &cl::print;
PROC pf2 = &cl::print;
z1.print(1);
(z1.*pf1)(2);
z2.print(3);
((&z2)-›*pf2)(4);
}
b5_5_3.cxx
main() {
char *p = new char[100];
char *q = new char[100];
delete p;
delete p;
}
b6_3_2.cxx
#include "stream.hxx"
int error (char * p)
{
cout ‹‹ p ‹‹ "\n";
return 1;
}
class tiny {
char v;
tiny assign(int i)
{v = (i&~63) ? (error("range error"),0) : i; return *this; }
public:
tiny (int i) { assign(i); }
tiny (tiny& t) { v = t.v; }
tiny operator=(tiny& t1) { v = t1.v; return *this; }
tiny operator=(int i) { return assign(i); }
int operator int() { return v; }
};
void main()
{
tiny c1 = 2;
tiny c2 = 62;
tiny c3 = (c2 - c1);
tiny c4 = c3;
int i = (c1 + c2);
c1 = (c2 + (2 * c1));
c2 = c1 - i;
c3 = c2;
}
b6_6.cxx
#include ‹stream.hxx›
extern int strcpy(char*, char*);
extern int strlen(char *);
struct string {
char *p;
int size;
inline string(int sz) { p = new char[size=sz]; }
string(char *);
inline ~string() { delete p; }
void operator=(string&);
string(string&);
};
string::string(char* s)
{
p = new char [size = strlen(s) + 1];
strcpy (p,s);
}
void string::operator=(string& a)
{
if (this == &a) return;
delete p;
p=new char[size=a.size];
strcpy(p,a.p);
}
string::string(string& a)
{
p=new char[size=a.size];
strcpy(p,a.p);
}
string g(string arg)
{
return arg;
}
main()
{
string s = "asdf";
s = g(s);
cout ‹‹ s.p ‹‹ "\n";
}
b6_7.cxx
#include ‹stream.hxx›
#include ‹string.h›
struct pair {
char * name;
int val;
};
class assoc {
pair * vec;
int max;
int free;
public:
assoc(int);
int& operator[](char*);
void print_all();
};
assoc::assoc(int s)
{
max = (s‹16) ? s : 16;
free = 0;
vec = new pair[max];
}
int& assoc::operator[](char * p)
/*
maintain a set of "pair"s
search for p,
return a reference to the integer part of its "pair"
make a new "pair" if "p" has not been seen
*/
{
register pair* pp;
for (pp=&vec[free-1]; vec‹=pp; pp--)
if (strcmp(p, pp-›name)-0) return pp-›val;
if (free==max) {// overflow: grow the vector
pair* nvec = new pair[max*2];
for (int i=0; i‹max; i++) nvec[i] = vec[i];
delete vec;
vec = nvec;
max = 2*max;
}
pp = &vec[free++];
pp-›name = new char[strlen(p)+1];
strcpy(pp-›name,p);
pp-›val = 0;
return pp-›val;
}