LDP/LDP/howto/linuxdoc/C++Programming-HOWTO.sgml

3669 lines
130 KiB
Plaintext
Raw Normal View History

<!doctype linuxdoc system>
<!--
************************** begin comment *****************************
The following is the HOW-TO for programming in C++.
This document is in the SGML format. You must use sgml package to
process this document
************************* end of comment *****************************
-->
<!--
************************** SGML USER GUIDE *****************************
The SGML user guide on linux is located at /usr/doc/sgml-tools
Read the example.sgml and guide.html documents.
Usage:
HTML sgml2html foo (Do not give extension .sgml here!!)
Text sgml2txt foo.sgml
Latex sgml2latex foo.sgml
2000-07-10 14:17:49 +00:00
(note: put extra dash - before language below, removed to compile)
Postscript sgml2latex -language=english -o ps foo.sgml
DVI sgml2latex -d foo.sgml
Lyx sgml2lyx foo.sgml
Richtext sgml2rtf foo.sgml
gnuinfo sgml2info foo.sgml
man sgml2txt -man foo.sgml
SGML sgmlcheck foo.sgml
************************* end of comment *****************************
-->
<article>
<!-- Title information -->
<title>C++ Programming HOW-TO
<!-- chapt change
C++ Programming HOW-TO
-->
<author>Al Dev (Alavoor Vasudevan)
<htmlurl url="mailto:alavoor@yahoo.com"
name="alavoor@yahoo.com">
2001-03-17 15:32:41 +00:00
<date>v35.0, 14 Mar 2001
<abstract>
2001-01-12 14:53:07 +00:00
This document provides a comprehensive list of C++ URL
pointers, links to C++ online textbooks, and programming tips on C++.
This document also provides a C++ library which imitates Java-language,
and which has various methods to avoid memory problems in C++. Using
this library you can compile Java's source code under C++.
This document serves as a "Home of C++ language".
The information given here will help you to program properly in C++ language
and applies to all the operating systems
2000-08-03 18:24:33 +00:00
that is - Linux, MS DOS, BeOS, Apple Macintosh OS, Microsoft Windows 95/98/NT/2000,
2000-07-10 14:17:49 +00:00
OS/2, IBM OSes (MVS, AS/400 etc..), VAX VMS, Novell Netware, all flavors of
Unix like Solaris, HPUX, AIX, SCO, Sinix, BSD, etc.. and to
all other operating systems which support "C++" compiler (it
2000-12-04 15:52:36 +00:00
means almost all the operating systems on this planet).
2001-01-12 14:53:07 +00:00
</abstract>
<!-- Table of contents -->
<toc>
<!-- Begin the document -->
<!--
*******************************************
************ End of Section ***************
*******************************************
<chapt>Introduction
-->
<sect>Introduction
<p>
2001-01-02 15:55:26 +00:00
The purpose of this document is to provide you with a comprehensive list of URL
pointers and programming tips on C++.
Also, this document provides a C++ library having Java-like String class,
string tokenizer, memory functions and many other functions, which
can be used in general C++ applications.
Also various examples are given here which demonstrate the usage of this library.
This document is not a textbook on C++, and there are already
several excellent "on-line Text books" on internet.
If you are new to C++ and you
never programmed in C++, then it is strongly suggested that you first read
the online C++ Textbooks given in the chapter
<ref id="onlinebooks" name="C++ Online Textbooks">
and then follow the subsequent chapters. It is suggested that you purchase
a textbook on C++ for reference from
<url name="online bookstores" url="http://www.amazon.com">.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect1> C++ v/s Java
<p>
C++ is one of the most powerful language and will be used for a long time in the future
inspite of emergence of Java. C++ runs <bf>extremely fast</bf> and is
2000-05-31 22:25:03 +00:00
in fact <bf> 10 to 20 times FASTER than </bf> Java. Java runs very slow
2001-01-02 15:55:26 +00:00
because it is a byte-code-interpreted language running on top of "virtual machine".
Java runs faster with JIT (Just-In-Time) compiler, but it is still slower than C++. And optimized
C++ program is about <bf>3 to 4 times faster</bf> than Java (with JIT compiler).
Then, why do people use Java? Because it is easier to program in Java,
as Java automates memory management, and programmers do not directly
deal with memory allocations. This document attempts
2001-01-02 15:55:26 +00:00
to automate the memory management in C++ to make it much more easy to use.
The library given here will make C++ look like Java and will enable "C++"
to compete with Java language.
Because of manual memory allocations, debugging the C++ programs consumes a
2001-01-02 15:55:26 +00:00
major portion of time. This document will give you some better ideas
and tips to reduce the debugging time.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect1>Which one "C", "C++" or Java ?
<p>
It is recommended you do programming in object-oriented "C++" for all your
application programming or general purpose programming. You can take full
advantage of object oriented facilities of C++. The C++ compiler is lot
more complex than "C" compiler and C++ programs may run bit slower than "C"
programs. But speed difference between "C" and "C++" is very minute - it
could be few milli-seconds which may have little impact
for real-time programming.
Since computer hardware is becoming cheaper and faster and memory
'RAM' is getting faster and cheaper, it is worth doing code in C++ rather than
"C" as time saved in clarity and re-usability of C++ code
offsets the slow speed.
Compiler optimizer options like -O or -O3 can speed up C++/C
which is not available in Java.
Nowadays, "C" language is primarily used for "systems programming" to develop
operating systems, device drivers etc..
<bf>Note: <it>Using the String, StringBuffer, StringTokenizer and StringReader classes
given in this howto, you can code in C++ which "exactly" looks like Java.
This document tries to close the gap between C++ and Java, by imitating Java
classes in C++</it></bf>
Java is platform independent language more suitable for developing GUI running
inside web-browsers (Java applets) but runs very slow. Prefer to
use web-server-side programming "Fast-CGI" with C++ and HTML, DHTML,
XML to get better performance. Hence, the golden rule is <it>"Web-server side programming
use C++ and web-client side (browser) programming use Java applets"</it>.
The reason is - the server-side OS (Linux) is under your control
and never changes, but you
will never know what the client side web-browser OS is. It can be Internet appliance device (embedded linux+netscape) or computers running Windows 95/98/NT/2000
or Linux, Apple Mac, OS/2, Netware, Solaris etc..
The advantage of Java language is that you can
create "Applets (GUI)" which can run on any client OS platform.
Java was created to replace the Microsoft Windows 95/NT GUI APIs like
MS Visual Basic or MS Visual C++.
In other words - "Java is the cross-platform Windows-GUI
API language of next century".
Many web-browsers like Netscape supports Java applets and web-browser like
Hot Java is written in java itself.
But the price you pay for cross-platform
portability is the performance, applications written in Java run very slow.
Hence, Java runs on "client" and C++ runs on servers.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect1>Problems facing the current C++ compilers
<p>
Since C++ is super-set of C, it got all the bad features of "C" language.
For example, in "C" programming - memory leaks, memory overflows are very common due
to usage of features like -
<code>
Datatype char * and char[]
String functions like strcpy, strcat, strncpy, strncat, etc..
Memory functions like malloc, realloc, strdup, etc..
</code>
The usage of <bf>char *</bf> and <bf>strcpy</bf> causes <it>horrible</it> memory
problems due to <it>"overflow"</it>,
2000-05-31 22:25:03 +00:00
<it>"fence past errors"</it>, <it>"step-on-others-toe"</it>
(hurting other variable's memory locations) or <it>"memory leaks"</it>.
The memory problems are extremely hard to debug and are
very time consuming to fix and trouble-shoot. Memory problems bring down
the productivity of programmers. This document helps in increasing the
productivity of programmers via different methods addressed to solve the
memory defects in "C++".
Memory related bugs are very tough to crack, and even experienced programmers
2001-01-02 15:55:26 +00:00
take several days or weeks to debug memory related problems. Memory
bugs may be hide inside the code for several months and can cause unexpected
2000-12-04 15:52:36 +00:00
program crashes. The memory bugs due to usage of
2001-01-02 15:55:26 +00:00
<bf>char *</bf> and <bf>pointers</bf> in C/C++
is costing $2 billion
every year in time lost due to debugging and downtime of programs. If you use
<bf>char *</bf> and <bf>pointers</bf>
in C++ then it is a very costly affair, especially if your program size is greater
than 10,000 lines of code.
Hence, the following techniques are proposed to overcome the faults of "C"
2001-01-02 15:55:26 +00:00
language. Give preference in the following order -
<enum>
<item> Use references instead of pointers.
<item> Java style String class (given in this howto) or STDLib string class.
<item> Character pointers (char *) in C++ <bf>limit the usage</bf> of char * to cases where you
cannot use the String class.
<item> Character pointers (char *) in C using extern linkage specification, if you
do not want to use (char *) in C++.
</enum>
To use "C char *", you would put
2000-07-10 14:17:49 +00:00
all your "C" programs in a separate file and link to "C++" programs using
2000-05-31 22:25:03 +00:00
the <it>linkage-specification</it> statement <bf>extern "C" </bf> -
<code>
extern "C" {
#include <stdlib.h>
}
extern "C" {
comp();
some_c_function();
}
</code>
2001-01-02 15:55:26 +00:00
The <bf>extern "C"</bf> is a linkage specification and is a flag that
everything within the enclosing block (brace-surrounded) uses C linkage,
not C++ linkage.
The
2000-07-05 17:23:44 +00:00
<bf>'String class'</bf>
2001-01-02 15:55:26 +00:00
utilises the constructor and destructor features to automate memory management
and provides access to functions like <it>ltrim</it>, <it>substring</it>,
etc..
See also related
<bf>'string class'</bf>
2001-01-02 15:55:26 +00:00
in the C++ compiler.
The <bf>string class</bf> is part of the standard GNU C++
library and provides many string manipulation functions.
Because the C++
<bf>'string class'</bf> and
2000-07-05 17:23:44 +00:00
<bf>'String class'</bf>
2001-01-02 15:55:26 +00:00
library provides many string manipulation functions, there is less need
to use the character pointer approach to write your own string functions.
Also, C++ programmers must be encouraged to use 'new', 'delete' operators instead
of using 'malloc' or 'free'.
The
2000-07-05 17:23:44 +00:00
<bf>'String class'</bf>
does everything
that <bf>char *</bf> or <bf>char []</bf> does. It can
completely replace <bf>char</bf> datatype. Plus added
benefit is that programmers do not have to worry
2000-12-04 15:52:36 +00:00
about the memory problems and memory allocation at all.
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-10-16 14:54:12 +00:00
-->
<sect1> COOP - C++ Object Oriented Programming-language
<p>
2001-01-02 15:55:26 +00:00
A problem with C++ is that it is a superset of C, and, although programmers
can use the good (object oriented) features of C++ and avoid the bad
features of C, there is nothing to force them to do so. So, many C++ programs
are written with no object oriented features and continue to use the bad
features of C that the use of C++ should have overcome.
Therefore, I propose that we create a new version of C++ that does not
allow the use of the bad features of C.
I propose that this new version of C++ be called <bf>COOP</bf> (say koop), which
is an acronym for
2000-10-16 14:54:12 +00:00
<bf>C++</bf>
2001-01-02 15:55:26 +00:00
<bf> O</bf>bject
<bf> O</bf>riented
<bf> P</bf>rogramming-language"
. COOP should be pronounced like chicken coop. (The logo of COOP language is
a big fat Hen inside coop!)
I propose that the file extension for COOP files be .coo, which will
not conflict with .c for C programs or .cpp for C++ programs.
To begin with write the COOP as a front end to C++. That is COOP
pre-processes the code syntax and then uses the standard C++ compiler
to compile the program.
COOP acts as a front end to C++ compiler.
The following are some other proposed features of COOP:
2000-10-16 14:54:12 +00:00
<itemize>
<item> Is a super-set of C++ language but will force programmer to
use obejct oriented programming.
<item> Pure Object-oriented langauge but retains syntax of C++.
<item> Remove all bad features of C++ in COOP.
<item> Prevent writing "C" like programming in COOP, something which C++ currently allows.
2001-01-02 15:55:26 +00:00
Delete all C features which are considered bad or redundant/duplicates,
2001-01-12 14:53:07 +00:00
like printf, fprintf, malloc, struct, free etc..
2001-01-02 15:55:26 +00:00
<item> No downward compatibility to "C" language.
<item> Code written in COOP will be easy to maintain and is easily understandable/readable.
2000-10-16 14:54:12 +00:00
<item> Code written in "COOP" will be re-usable (thru components, modules, objects).
2000-10-30 15:40:21 +00:00
Supports re-usable software components, thereby
facilitating Rapid Application Development.
2001-01-02 15:55:26 +00:00
<item> COOP is simple, robust, OOP, has bare mininum syntax (avoiding
confusing, redundant, extra constructs of C++)
2000-10-16 14:54:12 +00:00
</itemize>
2001-01-02 15:55:26 +00:00
Also borrow ideas from -
2000-10-16 14:54:12 +00:00
<itemize>
<item> Java - Sun Microsystem put lot of effort, and you can simply utilize that.
2001-01-02 15:55:26 +00:00
<item> C# - Microsoft put lot of efforts, and you can simply utilize them. Specs are at
2000-10-16 14:54:12 +00:00
<url url="http://msdn.microsoft.com/vstudio/nextgen/technology/csharpdownload.asp">
2001-01-02 15:55:26 +00:00
and see <url name="C# overview" url="http://msdn.microsoft.com/vstudio/nextgen/technology/csharpintro.asp">.
<item> Connective C++ at <url url="http://www.quintessent.com/products/cc++">.
2000-10-16 14:54:12 +00:00
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-12-04 15:52:36 +00:00
<chapt> String Class Varieties <label id = "String Variety">
2000-10-30 15:40:21 +00:00
-->
2000-12-04 15:52:36 +00:00
<sect> String Class Varieties <label id = "String Variety">
2000-10-30 15:40:21 +00:00
<p>
2001-01-02 15:55:26 +00:00
The string class is the most vital object in programming,
and string manipulations are most extensively used and they comprise of 20 to 60% of total code.
2000-10-30 15:40:21 +00:00
There are 3 variety of string classes. Ofcourse, you can build your own
string class by simply inheriting from these string classes -
<itemize>
<item> String class given in this document
2000-11-06 13:19:55 +00:00
<ref id="Appendix A" name="Appendix A String.h">
2000-10-30 15:40:21 +00:00
<p>
<item> GNU string class
2000-12-18 15:01:28 +00:00
<itemize>
<item> GNU C++ Library - Univ of Tech, Sydney
<url url="http://www.socs.uts.edu.au/doc/gnuinfo/libg++/libg++_18.html"> and
<url name="user's guide" url="http://www.socs.uts.edu.au/doc/gnuinfo/libg++">
<item> mirror site Gesellschaft
<url url="http://www-aix.gsi.de/doc/gnu/libg++_18.html#SEC23"> and
<url name="user's guide" url="http://www.gsi.de/doc/gnu/libg++_toc.html">
<item> mirror site Techno, Russia
<url url="http://www.techno.spb.ru/~xbatob/FAQ/GNU/libg++_19.html#SEC27"> and
<url name="user's guide" url="http://www.techno.spb.ru/~xbatob/FAQ/GNU/libg++_toc.html">
<item> mirror site Univ of Utah
<url url="http://www.math.utah.edu/docs/info/libg++_19.html#SEC27"> and
<url name="user's guide" url="http://www.math.utah.edu/docs/info/libg++_toc.html">
</itemize>
2000-10-30 15:40:21 +00:00
<p>
<item> Qt String class at <url url="http://doc.trolltech.com/qstring.html">
mirror at
<url url="http://www.cs.berkeley.edu/~dmartin/qt/qstring.html">
2000-12-18 15:01:28 +00:00
<p>
2001-01-02 15:55:26 +00:00
<item> If none of these alternatives are suitable, you can build
your own string class. You can start with one or more of the
pre-built classes listed above (by using single or multiple inheritance.)
2000-10-30 15:40:21 +00:00
</itemize>
2000-12-18 15:01:28 +00:00
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect1> Multiple Inheritance - Sample Custom String class
<p>
2001-01-02 15:55:26 +00:00
As mentioned above, you can build your own custom string class from the
pre-built classes by single or multiple inheritance. In this section
we will build a sample custom string class by using multiple inheritance,
inheriting from the GNU string class and the string class presented in Appendix H.
Start by downloading the sample file 'string_multi.h' from
<ref id="Appendix A">
. That file is reproduced below:
2000-12-18 15:01:28 +00:00
<code>
// ******************************************************************
// Sample program to demonstrate constructing your own string class
// by deriving from the String class and stdlib's "string" class
// ******************************************************************
#ifndef __STRING_MULTI_H_
#define __STRING_MULTI_H_
#include <string>
#include "String.h"
// Important Notes: In C++ the constructors, destructors and copy
// operator are NOT inherited by the derived classes!!
// Hence, if the operators like =, + etc.. are defined in
// base class and those operators use the base class's contructors
// then you MUST define equivalent constructors in the derived
// class. See the sample given below where constructors mystring(),
// mystring(char[]) are defined.
//
// Also when you use operator as in atmpstr + mstr, what you are really
// calling is atmpstr.operator+(mstr). The atmpstr is declared a mystring
class mystring:public String, string
{
public:
mystring():String() {} // These are needed for operator=, +
mystring(char bb[]):String(bb) {} // These are needed for operator=, +
mystring(char bb[], int start, int slength):String(bb, start, slength) {}
mystring(int bb):String(bb) {} // needed by operator+
mystring(unsigned long bb):String(bb) {} // needed by operator+
mystring(long bb):String(bb) {} // needed by operator+
mystring(float bb):String(bb) {} // needed by operator+
mystring(double bb):String(bb) {} // needed by operator+
mystring(const String & rhs):String(rhs) {} // Copy Constructor needed by operator+
mystring(StringBuffer sb):String(sb) {} // Java compatibility
mystring(int bb, bool dummy):String(bb, dummy) {} // for StringBuffer class
int mystraa; // customizations of mystring
private:
int mystrbb; // customizations of mystring
};
#endif // __STRING_MULTI_H_
</code>
2000-10-30 15:40:21 +00:00
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-07-05 17:23:44 +00:00
<chapt> Download String <label id = "Download String">
-->
2000-07-05 17:23:44 +00:00
<sect> Download String <label id = "Download String">
<p>
All the programs, examples are given in Appendix of this document.
2000-07-05 17:23:44 +00:00
You can download as a single tar zip, the String class, libraries
and example programs from
<itemize>
<item> Go here and click on C++Programming howto.tar.gz file <url url="http://www.aldev.8m.com">
2001-02-01 14:40:35 +00:00
<item> Mirror sites : <url url="http://aldev.webjump.com">,
<url url="http://www.angelfire.com/nv/aldev" name="angelfire">,
<url url="http://www.geocities.com/alavoor/index.html" name="geocities">,
<url url="http://aldev.virtualave.net" name="virtualave">,
<url url="http://aldev.bizland.com" name="bizland">,
<url url="http://members.theglobe.com/aldev/index.html" name="theglobe">,
<url url="http://members.spree.com/technology/aldev" name="spree">,
<url url="http://homepages.infoseek.com/~aldev1/index.html" name="infoseek">,
<url url="http://www3.bcity.com/aldev" name="bcity">,
<url url="http://aldev.50megs.com" name="50megs">
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-07-05 17:23:44 +00:00
<chapt> Usage of String class
-->
2000-07-05 17:23:44 +00:00
<sect> Usage of String class
<p>
2000-07-05 17:23:44 +00:00
To use String class, you should first refer to a
sample program "example_String.cpp"
given in
<ref id ="Appendix A" name="Appendix A">
and the String class which is given in
2000-11-06 13:19:55 +00:00
<ref id ="Appendix A" name="Appendix A">.
2000-07-05 17:23:44 +00:00
The
2000-07-05 17:23:44 +00:00
<bf>'String class'</bf>
is a complete replacement for char and char * datatype.
You can use
2000-07-05 17:23:44 +00:00
<bf>'String class'</bf>
just like char and get much more functionalities.
2000-07-10 14:17:49 +00:00
You should link with the library 'libString.a' which you can build from the
makefile given in
2000-11-06 13:19:55 +00:00
<ref id ="Appendix A" name="Appendix A"> and copy the library to
2000-07-10 14:17:49 +00:00
/usr/lib or /lib directory where all the "C++" libraries are located. To use
2000-07-05 17:23:44 +00:00
the 'libString.a' compile your programs like -
<code>
2000-07-05 17:23:44 +00:00
g++ example.cpp -lString
</code>
See illustration sample code as given below -
<code>
2000-07-05 17:23:44 +00:00
String aa;
2001-01-12 14:53:07 +00:00
aa = " Creating an Universe is very easy ";
2000-12-04 15:52:36 +00:00
// You can use aa.val() like a 'char *' variable in programs
for (unsigned long tmpii = 0; tmpii < aa.length(); tmpii++)
{
2000-07-10 14:17:49 +00:00
//fprintf(stdout, "aa.val()[%ld]=%c ", tmpii, aa.val()[tmpii]);
fprintf(stdout, "aa[%ld]=%c ", tmpii, aa[tmpii]);
}
// Using pointers on 'char *' val ...
2000-07-10 14:17:49 +00:00
for (char *tmpcc = aa.val(); *tmpcc != 0; tmpcc++)
{
2000-07-10 14:17:49 +00:00
fprintf(stdout, "aa.val()=%c ", *tmpcc);
}
</code>
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect1> Operators
<p>
The
2000-07-05 17:23:44 +00:00
<bf>'String class'</bf>
provides these operators :-
<itemize>
<item> Equal to <bf>==</bf>
<item> Not equal to <bf>!=</bf>
<item> Assignment <bf>=</bf>
<item> Add to itself and Assignment <bf>+=</bf>
<item> String concatenation or addition <bf>+</bf>
</itemize>
For example to use operators -
<code>
2000-07-05 17:23:44 +00:00
String aa;
String bb("Bill Clinton");
aa = "put some value string"; // assignment operator
aa += "add some more"; // Add to itself and assign operator
aa = "My name is" + " Alavoor Vasudevan "; // string cat operator
if (bb == "Bill Clinton") // boolean equal to operator
2000-10-30 15:40:21 +00:00
cout << "bb is equal to 'Bill Clinton' " << endl;
if (bb != "Al Gore") // boolean 'not equal' to operator
cout << "bb is not equal to 'Al Gore'" << endl;
</code>
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect1> Functions
<p>
2000-07-05 17:23:44 +00:00
The functions provided by String class has the <bf>same name</bf>
2000-08-03 18:24:33 +00:00
as that of Java language's
2000-07-05 17:23:44 +00:00
String class. The function names and the behaviour is <bf>exactly</bf> same
2000-12-04 15:52:36 +00:00
as that of Java's String class. StringBuffer class is also provided.
2000-08-03 18:24:33 +00:00
This will facilitate portability of code
2000-07-05 17:23:44 +00:00
between Java and C++ (you can cut and paste and do minimum changes to code).
2000-08-03 18:24:33 +00:00
The code from Java's function body can be copied into C++ member function
body and with very mininum changes the code will compile under C++.
Another advantage is that developers coding in
both Java and C++ do not need to remember two
different syntax or function names.
2000-07-05 17:23:44 +00:00
For example to convert integer to string do -
<code>
2000-07-05 17:23:44 +00:00
String aa;
aa = 34; // The '=' operator will convert int to string
2000-07-10 14:17:49 +00:00
cout << "The value of aa is : " << aa.val() << endl;
aa = 234.878; // The '=' operator will convert float to string
2000-07-10 14:17:49 +00:00
cout << "The value of aa is : " << aa.val() << endl;
aa = 34 + 234.878;
2000-07-10 14:17:49 +00:00
cout << "The value of aa is : " << aa.val() << endl;
// The output aa will be '268.878'
2000-07-05 17:23:44 +00:00
// You must cast String to convert
2000-10-30 15:40:21 +00:00
aa = (String) 34 + " There can be infinite number of universes!! " + 234.878;
2000-07-10 14:17:49 +00:00
cout << "The value of aa is : " << aa.val() << endl;
2000-10-30 15:40:21 +00:00
// The output aa will be '34 There can be infinite number of universes!! 234.878'
</code>
2000-12-18 15:01:28 +00:00
Refer to
<ref id="Appendix A" name="Appendix A String.h">
for details about the String class function names. The same file String.h is
reproduced here in next section.
<!--
*******************************************
************ End of Section ***************
*******************************************
<chapt> String.h file
-->
<sect> String.h file
<p>
2001-02-01 14:40:35 +00:00
In C++ (or any object oriented language), you just read the "class data-structure"
(i.e. interface) to begin using that object.
You just need to understand the interface and not the implementation of the interface.
In case of String class, you just need to read and
2001-01-12 14:53:07 +00:00
understand the String class in String.h file. You <bf>do not need</bf> to read
the entire implementation (String.cpp) in order to use String class.
The object oriented classes are real time saver and they
<bf>very neatly hide</bf> the implementation.
2001-02-01 14:40:35 +00:00
(In object oriented Java language there is the equivalent called <bf>'Intefaces'</bf>
, which hides the implementation details.)
2000-12-18 15:01:28 +00:00
Given below is <bf>String.h</bf> file and
2001-01-12 14:53:07 +00:00
see also
2000-12-18 15:01:28 +00:00
<ref id="Appendix A" name="Appendix A String.h">
<code>
2001-01-12 14:53:07 +00:00
//
// Author : Al Dev Email: alavoor@yahoo.com
// Use string class or String class
//
// To prevent memory leaks - a char class to manage character variables
// Always prefer to use String or string class
// instead of char[] or char *
//
2000-12-18 15:01:28 +00:00
#ifndef __STRING_H_
#define __STRING_H_
#include <iostream> // do not use iostream as program becomes bulky..
#include <stdio.h> // for FILE and sprintf()
#include <list.h> // for list
const short INITIAL_SIZE = 50;
const short NUMBER_LENGTH = 300;
const int MAX_ISTREAM_SIZE = 2048;
class StringBuffer;
// a small class with a VERY MINIMUM of functions and variables...
// This class to be kept small...
class String
{
public:
String();
2001-02-13 14:40:24 +00:00
String(const char bb[]); // needed by operator+
String(const char bb[], int start, int slength); // subset of chars
2000-12-18 15:01:28 +00:00
String(int bb); // needed by operator+
String(unsigned long bb); // needed by operator+
String(long bb); // needed by operator+
String(float bb); // needed by operator+
String(double bb); // needed by operator+
String(const String & rhs); // Copy Constructor needed by operator+
String(StringBuffer sb); // Java compatibility
String(int bb, bool dummy); // for StringBuffer class
virtual ~String(); // Made virtual so that when base class is deleted
// then the derived class destructor is called.
2001-02-13 14:40:24 +00:00
char *val() {return sval;} // It is not safe to make sval public
2000-12-18 15:01:28 +00:00
// Functions below imitate Java language's String object
unsigned long length() { return strlen(sval); }
char charAt(int where);
void getChars(int sourceStart, int sourceEnd,
char target[], int targetStart);
char* toCharArray();
char* getBytes();
bool equals(String str2); // See also == operator
bool equals(char *str2); // See also == operator
bool equalsIgnoreCase(String str2);
bool regionMatches(int startIndex, String str2,
int str2StartIndex, int numChars);
bool regionMatches(bool ignoreCase, int startIndex,
String str2, int str2StartIndex, int numChars);
String toUpperCase();
String toLowerCase();
bool startsWith(String str2);
bool startsWith(char *str2);
bool endsWith(String str2);
bool endsWith(char *str2);
int compareTo(String str2);
int compareTo(char *str2);
int compareToIgnoreCase(String str2);
int compareToIgnoreCase(char *str2);
int indexOf(char ch, int startIndex = 0);
int indexOf(char *str2, int startIndex = 0);
int indexOf(String str2, int startIndex = 0);
int lastIndexOf(char ch, int startIndex = 0);
int lastIndexOf(char *str2, int startIndex = 0);
int lastIndexOf(String str2, int startIndex = 0);
String substring(int startIndex, int endIndex = 0);
String replace(char original, char replacement);
String replace(char *original, char *replacement);
String trim(); // See also overloaded trim()
String concat(String str2); // See also operator +
String concat(char *str2); // See also operator +
String reverse(); // See also overloaded reverse()
String deleteCharAt(int loc);
String deleteStr(int startIndex, int endIndex); // Java's "delete()"
String valueOf(char ch)
{char aa[2]; aa[0]=ch; aa[1]=0; return String(aa);}
String valueOf(char chars[]){ return String(chars);}
String valueOf(char chars[], int startIndex, int numChars);
String valueOf(bool tf)
{if (tf) return String("true"); else return String("false");}
String valueOf(int num){ return String(num);}
String valueOf(long num){ return String(num);}
String valueOf(float num) {return String(num);}
String valueOf(double num) {return String(num);}
// See also StringBuffer class in this file given below
// ---- End of Java like String object functions -----
//////////////////////////////////////////////////////
// List of additonal functions not in java
//////////////////////////////////////////////////////
String ltrim();
void ltrim(bool dummy); // dummy to get different signature
String rtrim();
void rtrim(bool dummy); // dummy to get different signature
void chopall(char ch='\n'); // removes trailing character 'ch'
void chop(); // removes one trailing character
void roundf(float input_val, short precision);
void decompose_float(long *integral, long *fraction);
void roundd(double input_val, short precision);
void decompose_double(long *integral, long *fraction);
2001-03-17 15:32:41 +00:00
void explode(char *separator); // see also token() and overloaded explode()
String *explode(int & strcount, char separator = ' '); // see also token()
2000-12-18 15:01:28 +00:00
void implode(char *glue);
void join(char *glue);
String repeat(char *input, unsigned int multiplier);
String tr(char *from, char *to); // translate characters
String center(int padlength, char padchar = ' ');
String space(int number = 0, char padchar = ' ');
String xrange(char start, char end);
String compress(char *list = " ");
String left(int slength = 0, char padchar = ' ');
String right(int slength = 0, char padchar = ' ');
String overlay(char *newstr, int start = 0, int slength = 0, char padchar = ' ');
String at(char *regx); // matches first match of regx
String before(char *regx); // returns string before regx
String after(char *regx); // returns string after regx
String mid(int startIndex = 0, int length = 0);
bool isNull();
bool isInteger();
bool isInteger(int pos);
bool isNumeric();
bool isNumeric(int pos);
bool isEmpty(); // same as length() == 0
bool isUpperCase();
bool isUpperCase(int pos);
bool isLowerCase();
bool isLowerCase(int pos);
bool isWhiteSpace();
bool isWhiteSpace(int pos);
bool isBlackSpace();
bool isBlackSpace(int pos);
bool isAlpha();
bool isAlpha(int pos);
bool isAlphaNumeric();
bool isAlphaNumeric(int pos);
bool isPunct();
bool isPunct(int pos);
bool isPrintable();
bool isPrintable(int pos);
bool isHexDigit();
bool isHexDigit(int pos);
bool isCntrl();
bool isCntrl(int pos);
bool isGraph();
bool isGraph(int pos);
void clear();
int toInteger();
long parseLong();
double toDouble();
2001-03-17 15:32:41 +00:00
String token(char separator = ' '); // ref StringTokenizer, explode()
2000-12-18 15:01:28 +00:00
String crypt(char *original, char *salt);
String getline(FILE *infp = stdin); // see also putline()
//String getline(fstream *infp = stdin); // see also putline()
void putline(FILE *outfp = stdout); // see also getline()
//void putline(fstream *outfp = stdout); // see also getline()
void swap(String aa, String bb); // swap aa to bb
String *sort(String aa[]); // sorts array of strings
String sort(int startIndex = 0, int length = 0); // sorts characters inside a string
int freq(char ch); // returns the number of distinct, nonoverlapping matches
void Format(const char *fmt, ...);
String replace (int startIndex, int endIndex, String str);
void substring(int startIndex, int endIndex, bool dummy);
void reverse(bool dummy); // dummy to get different signature
String deleteCharAt(int loc, bool dummy);
String deleteStr(int startIndex, int endIndex, bool dummy);
void trim(bool dummy); // dummy to get different signature
String insert(int index, String str2);
String insert(int index, String str2, bool dummy);
String insert(int index, char ch);
String insert(int index, char ch, bool dummy);
String insert(char *newstr, int start = 0, int length = 0, char padchar = ' ');
2001-01-12 14:53:07 +00:00
String dump(); // Dump the string like 'od -c' (octal dump) does
2000-12-18 15:01:28 +00:00
// required by java's StringBuffer
void ensureCapacity(int capacity);
void setLength(int len);
void setCharAt(int where, char ch);
// required by java's Integer class, Long, Double classes
int parseInt(String ss) {return ss.toInteger();}
int parseInt(char *ss)
{String tmpstr(ss); return tmpstr.toInteger();}
long parseLong(String ss) {return ss.parseLong();}
long parseLong(char *ss)
{String tmpstr(ss); return tmpstr.parseLong();}
float floatValue() {return (float) toDouble(); }
double doubleValue() {return toDouble(); }
///////////////////////////////////////////////
// List of duplicate function names
///////////////////////////////////////////////
// char * c_str() // use val()
// bool find(); // Use regionMatches()
// bool search(); // Use regionMatches()
// bool matches(); // Use regionMatches()
// int rindex(String str2, int startIndex = 0); Use lastIndexOf()
// String blanks(int slength); // Use repeat()
// String append(String str2); // Use concat() or + operator
// String prepend(String str2); // Use + operator. See also append()
2001-03-17 15:32:41 +00:00
// String split(char separator = ' '); // Use token()
2000-12-18 15:01:28 +00:00
bool contains(char *str2, int startIndex = 0); // use indexOf()
// void empty(); Use is_empty()
// void vacuum(); Use clear()
// void erase(); Use clear()
// void zero(); Use clear()
// bool is_float(); Use is_numeric();
// bool is_decimal(); Use is_numeric();
// bool is_Digit(); Use is_numeric();
// float float_value(); Use toDouble();
// float tofloat(); Use toDouble();
// double double_value(); Use toDouble();
// double numeric_value(); Use toDouble();
// int int_value(); Use toInteger()
// int tonumber(); Use toInteger()
// String get(); Use substring() or val() but prefer java's substring
// String getFrom(); Use substring() or val() but prefer java's substring
// String head(int len); Use substring(0, len)
// String tail(int len); Use substring(length()-len, length())
// String cut(); Use deleteCharAt() or deleteStr()
// String cutFrom(); Use deleteCharAt() or deleteStr()
// String paste(); Use insert()
// String fill(); Use replace()
// char firstChar(); // Use substring(0, 1);
// char lastChar(); // Use substring(length()-1, length());
// String findNext(); Use token()
// begin(); iterator. Use operator [ii]
// end(); iterator. Use operator [ii]
// copy(); Use assignment = operator, String aa = bb;
// clone(); Use assignment = operator, String aa = bb;
// All Operators ...
String operator+ (const String & rhs);
friend String operator+ (const String & lhs, const String & rhs);
String& operator+= (const String & rhs); // using reference will be faster
String& operator= (const String & rhs); // using reference will be faster
bool operator== (const String & rhs); // using reference will be faster
bool operator== (const char *rhs);
bool operator!= (const String & rhs);
bool operator!= (const char *rhs);
char operator [] (unsigned long Index) const;
char& operator [] (unsigned long Index);
friend ostream & operator<< (ostream & Out, const String & str2);
friend istream & operator>> (istream & In, String & str2);
static list<String> explodeH; // list head
protected:
char *sval; // Not safe to make sval public
inline void verifyIndex(unsigned long index) const;
inline void verifyIndex(unsigned long index, char *aa) const;
void _str_cat(char bb[]);
void _str_cat(int bb);
void _str_cat(unsigned long bb);
void _str_cat(float bb);
private:
// Note: All the private variables and functions begin
// with _ (underscore)
//static String *_global_String; // for use in add operator
//inline void _free_glob(String **aa);
void _str_cpy(char bb[]);
void _str_cpy(int bb); // itoa
void _str_cpy(unsigned long bb);
void _str_cpy(float bb); // itof
bool _equalto(const String & rhs, bool type = false);
bool _equalto(const char *rhs, bool type = false);
String *_pString; // temporary pointer for internal use..
inline void _allocpString();
inline void _reverse();
inline void _deleteCharAt(int loc);
inline void _deleteStr(int startIndex, int endIndex);
inline void _trim();
inline void _ltrim();
inline void _rtrim();
inline void _substring(int startIndex, int endIndex);
};
// Imitate Java's StringBuffer object
// This class is provided so that the Java code is
// portable to C++, requiring minimum code changes
// Note: While coding in C++ DO NOT use this class StringBuffer,
// this is provided only for compiling code written in Java
// which is cut/pasted inside C++ code.
class StringBuffer: public String
{
public:
StringBuffer();
StringBuffer(int size);
StringBuffer(String str);
~StringBuffer();
int capacity() {return strlen(sval);}
StringBuffer append(String str2)
{ *this += str2; return *this;} // See also operator +
StringBuffer append(char *str2)
{ *this += str2; return *this;} // See also operator +
StringBuffer append(int bb)
{ *this += bb; return *this;} // See also operator +
StringBuffer append(unsigned long bb)
{ *this += bb; return *this;} // See also operator +
StringBuffer append(float bb)
{ *this += bb; return *this;} // See also operator +
StringBuffer append(double bb)
{ *this += bb; return *this;} // See also operator +
StringBuffer insert(int index, String str2)
{ return String::insert(index, str2, true);}
StringBuffer insert(int index, char ch)
{ return String::insert(index, ch, true);}
StringBuffer reverse()
{ String::reverse(true); return *this;}
// Java's "delete()". Cannot use name delete in C++
StringBuffer deleteStr(int startIndex, int endIndex)
{ String::deleteStr(startIndex, endIndex, true); return *this;}
StringBuffer deleteCharAt(int loc)
{ String::deleteCharAt(loc, true); return *this;}
StringBuffer substring(int startIndex, int endIndex = 0)
{ String::substring(startIndex, endIndex, true); return *this;}
};
static String Integer("0"); // java's Integer.parseInt(String);
static String Long("0"); // java's Long.parseLong(String);
// Imitate java's Float class and Float.floatValue()
// provided to compile java code in C++
class Float: public String
{
public:
Float(String str);
Float valueOf(String str2) {return Float(str2);}
float floatValue() {return (float) toDouble(); }
};
// Imitate java's Double class and Double.doubleValue()
// provided to compile java code in C++
class Double: public String
{
public:
Double(String str);
Double valueOf(String str2) {return Double(str2);}
double doubleValue() {return toDouble(); }
};
// Imitate java's StringTokenizer class
// provided to compile java code in C++ and vice-versa
class StringTokenizer: public String
{
public:
StringTokenizer(String str);
StringTokenizer(String str, String delimiters);
StringTokenizer(String str, String delimiters, bool dflag);
~StringTokenizer();
int countTokens();
bool hasMoreElements();
bool hasMoreTokens();
String nextElement(); // in java returns type 'Object'
String nextToken();
String nextToken(String delimiters);
private:
2001-01-12 14:53:07 +00:00
int mvCurrentPosition; // current index on string
int mvTotalTokens;
int mvRemainingTokens;
char * mvpListOfDl; // list of delimiters
char * mvpWorkStr; // temp work string
char * mvpOrigStr; // original string passed
bool mvDlFlag; // delimiter flag
inline void vPrepWorkStr(char *delimiters = NULL);
2000-12-18 15:01:28 +00:00
};
// Imitate java's StringReader class
// provided to compile java code in C++
class StringReader: public String
{
public:
StringReader(String str);
void close() {} // close the stream
void mark(int readAheadLimit);
bool markSupported() {return true;} // tell whether this stream supports the mark() operation, which it does
int read();
int read(char cbuf[], int offset, int length);
bool ready() {return true;} // tell whether this stream is ready to read
void reset();
long skip(long ii);
private:
unsigned long _curpos;
unsigned long _mark_pos;
};
// Imitate java's StringWriter class
// provided to compile java code in C++
class StringWriter: public String
{
public:
StringWriter();
StringWriter(int bufferSize);
void close() {clear();}
void flush() {clear();}
StringBuffer getBuffer() {return (StringBuffer) *this;}
String toString() {return (String) *this;}
void write(int);
void write(String);
void write(char *str1);
void write(char str1[], int startIndex, int endIndex);
void write(String str1, int startIndex, int endIndex);
};
// Global variables are defined in String.cpp
#endif // __STRING_H_
</code>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-12-04 15:52:36 +00:00
<chapt change> Renaming the String class
2000-11-13 15:38:38 +00:00
-->
2000-12-04 15:52:36 +00:00
<sect> Renaming the String class
2000-11-13 15:38:38 +00:00
<p>
2000-12-11 15:15:51 +00:00
<sect1> Case 1: Simple rename
<p>
If you do not like the String class name then you
can use <bf>"typedef"</bf> to rename the String class.
In all the files where you do include String.h, insert these lines:
<code>
// If you do not like the class name String, then you can rename using typedef
typedef String StringSomethingElseIwant;
// Your remaing code may be like this ....
int main()
{
StringSomethingElseIwant aa_renstr;
aa_renstr = "I renamed the String Class using typedef";
.......etc...
}
</code>
See the
<url url="http://www.angelfire.com/nv/aldev/cpphowto/example_String.cpp"
name="example_String.cpp">.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect1> Case 2: Resolve conflict
<p>
If there is a conflict with another class-name having the same name, and
you want to use both this class and conflicting class then you use this
technique -
in all the files where you do include String.h, insert these lines:
2000-11-13 15:38:38 +00:00
<code>
#define String String_somethingelse_which_I_want
#include "String.h"
#undef String
2000-12-11 15:15:51 +00:00
#include "ConflictingString.h" // This also has String class...
2000-11-13 15:38:38 +00:00
// All your code goes here...
main()
{
String_somethingelse_which_I_want aa;
2000-12-11 15:15:51 +00:00
String bb; // This string class from conflicting string class
2000-11-13 15:38:38 +00:00
aa = " some sample string";
2000-12-11 15:15:51 +00:00
bb = " another string abraka-dabraka";
2000-11-13 15:38:38 +00:00
.......
}
</code>
2000-12-11 15:15:51 +00:00
The pre-processor will replace all literals of String
to "String_somethingelse_which_I_want" and immdiately undefines String.
After undef the conflicting string class header file is included which
defines the "String" class.
2000-11-13 15:38:38 +00:00
<!--
*******************************************
************ End of Section ***************
*******************************************
<chapt change> File Class
-->
<sect> File Class
<p>
You would use the File class to manipulate the operating system files.
2001-01-12 14:53:07 +00:00
This class is an imitation of Java's File class and will be very useful
2000-11-13 15:38:38 +00:00
in C++ programming. Using this File class in C++ you can do
if file <bf>exists()</bf> ?,
if directory <bf>exists()</bf> ?,
file <bf>length()</bf> and other functions.
<itemize>
<item> C++ File class is at
File.h
<url url="http://www.angelfire.com/nv/aldev/cpphowto/File.h">
and File.cpp
<url url="http://www.angelfire.com/nv/aldev/cpphowto/File.cpp">
<p>
<item> Java java.io.File class definition <url url="http://java.sun.com/j2se/1.3/docs/api/java/io/File.html">
<item> Quick Reference on File Class <url url="http://unicornsrest.org/reference/java/qref11/java.io.File.html">
<item> File Class summary <url url="http://www.idi.ntnu.no/~database/SIF8020/java-api/java.io.File.html">
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-12-18 15:01:28 +00:00
<chapt> C++ Zap (Delete) function <label id="zap">
-->
2000-12-18 15:01:28 +00:00
<sect> C++ Zap (Delete) function <label id="zap">
<p>
The
<bf>delete</bf> and
<bf>new</bf>
2000-12-18 15:01:28 +00:00
operators in C++ are much better than the malloc and free functions of C.
2000-12-04 15:52:36 +00:00
Consider using new and zap (delete function) instead of malloc and free
as much as possible.
To make
<bf>delete</bf>
2000-12-18 15:01:28 +00:00
operators even more cleaner, make a Zap() inline function. Define
2000-12-11 15:15:51 +00:00
a zap() function like this:
<code>
2001-01-12 14:53:07 +00:00
// Put an assert to check if x is NULL, this is to catch
2000-12-04 15:52:36 +00:00
// program "logic" errors early. Even though delete works
2000-10-30 15:40:21 +00:00
// fine with NULL by using assert you are actually catching
2000-12-04 15:52:36 +00:00
// "bad code" very early
2000-10-30 15:40:21 +00:00
2000-12-11 15:15:51 +00:00
// Defining Zap using templates
template <class T>
inline void zap(T& x) {
assert(x != NULL);
delete x;
x = NULL;
}
2000-04-28 18:00:14 +00:00
2000-12-11 15:15:51 +00:00
template <class T*>
inline void zap(T*& x) {
assert(x != NULL);
delete x;
x = NULL;
}
// For delete array
template <class T>
inline void zaparr(T& x) {
assert(x != NULL);
delete [] x;
x = NULL;
}
</code>
2000-12-18 15:01:28 +00:00
The zap() function will delete the pointer and set it NULL.
2000-04-28 18:00:14 +00:00
This will ensure that even if multiple zap()'s are called on the
same deleted pointer then the
program will not crash. For example -
<code>
2000-04-28 18:00:14 +00:00
zap(pFirstname);
2000-12-04 15:52:36 +00:00
//zap(pFirstname); // no core dumps. Because pFirstname is NULL now
//zap(pFirstname); // no core dumps. Because pFirstname is NULL now
2000-04-28 18:00:14 +00:00
zap(pLastname);
zap(pJobDescription);
2000-12-11 15:15:51 +00:00
int *iiarray = new int[10];
zaparr(iiarray);
</code>
There is nothing magical about this, it just saves
2000-04-28 18:00:14 +00:00
repetative code, saves typing time and makes programs more readable. The
C++ programmers often forget to reset the deleted pointer
to NULL, and this causes annoying
problems causing core dumps and crashes. The zap() takes care of
this automatically.
2000-12-18 15:01:28 +00:00
Do not stick a typecast in the zap() function -- if something errors out on the
above zap() function it likely has another error somewhere.
Also
<ref id="my_malloc" name="my_malloc()">
, my_realloc() and my_free() should be used
instead of malloc(), realloc() and free(), as they
are much cleaner and have additional checks.
2000-07-05 17:23:44 +00:00
For an example, see the file "String.h" which is using
the
<ref id="my_malloc" name="my_malloc()">
and my_free() functions.
2000-05-31 22:25:03 +00:00
<bf>WARNING :</bf> Do not use free() to free memory allocated with 'new'
or 'delete' to free memory allocated with malloc. If you do, then
2000-12-04 15:52:36 +00:00
results will be unpredictable.
2000-12-11 15:15:51 +00:00
See the zap examples in
<url url="http://www.angelfire.com/nv/aldev/cpphowto/example_String.cpp"
name="example_String.cpp">.
<!--
*******************************************
************ End of Section ***************
*******************************************
<chapt> Pointers are problems <label id="pointers">
-->
<sect> Pointers are problems <label id="pointers">
<p>
2000-05-31 22:25:03 +00:00
Pointers are not required for general purpose programming. In modern
2000-12-04 15:52:36 +00:00
languages like Java there is no support for pointers. Pointers make
2000-05-31 22:25:03 +00:00
the programs messy and programs using pointers are very hard to read.
Avoid using pointers as much as possible and use references. Pointers are really a
2001-01-12 14:53:07 +00:00
great pain. It is possible to write an application without using pointers.
2000-10-09 16:27:45 +00:00
<it>You should pointers only in those cases where references will not work.</it>
2000-05-31 22:25:03 +00:00
A <bf>reference</bf> is an alias; when you create a reference, you initialize
it with the name of another object, the target. From the moment on, the reference
acts as an alternative name of the target, and anything you do to the reference
is really done to the target.
<bf>Syntax of References:</bf> Declare a reference by writing the type, followed by
the reference operator (&), followed by the reference name. References
<bf>MUST</bf> be initialized at the time of creation.
For example -
<code>
int weight;
int & rweight = weight;
DOG aa;
DOG & rDogRef = aa;
</code>
<it>Do's</it> of references -
<itemize>
<item>Do use references to create an alias to an object
<item>Do initialize all references
<item>Do use references for high efficiency and performance of program.
<item>Do use <bf>const</bf> to protect references and pointers whenever possible.
</itemize>
<it>Do not's</it> of references -
<itemize>
2000-12-04 15:52:36 +00:00
<item><bf>IMPORTANT: </bf>Don't use references to NULL objects
<item>Don't confuse the address of operator &amp with reference operator. The references
are used in the declarations section (see Syntax of References above).
<item>Don't try to reassign a reference
<item>Don't use pointers if references will work
<item>Don't return a reference to a local object
<item>Don't pass by reference if the item referred to may go out of scope
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
<chapt> Usage of my_malloc and my_free <label id="my_malloc">
-->
<sect> Usage of my_malloc and my_free <label id="my_malloc">
<p>
Try to avoid using malloc and realloc as much as possible and use <bf>new</bf>
and <bf><ref id="zap" name="zap">(delete)</bf>. But sometimes you may need to
use the "C" style memory allocations in "C++". Use the functions
<bf>my_malloc()</bf> ,
<bf>my_realloc()</bf> and
<bf>my_free()</bf>.
These functions do proper allocations and initialisations and try to prevent
memory problems. Also these functions (in DEBUG mode) can keep track
of memory allocated and print total memory usage before and after the program
is run. This tells you if there are any memory leaks.
The my_malloc and my_realloc is defined as below. It allocates little more memory
(SAFE_MEM = 5) and initializes the space and if it cannot allocate it exits the
2000-11-06 13:19:55 +00:00
program. The 'call_check(), remove_ptr()' functions are active only
when DEBUG_MEM is defined in
makefile and are assigned to
((void)0) i.e. NULL
for non-debug production release. They enable the total-memory used tracing.
<code>
void *local_my_malloc(size_t size, char fname[], int lineno)
{
size_t tmpii = size + SAFE_MEM;
void *aa = NULL;
aa = (void *) malloc(tmpii);
if (aa == NULL)
raise_error_exit(MALLOC, VOID_TYPE, fname, lineno);
memset(aa, 0, tmpii);
call_check(aa, tmpii, fname, lineno);
return aa;
}
char *local_my_realloc(char *aa, size_t size, char fname[], int lineno)
{
remove_ptr(aa, fname, lineno);
unsigned long tmpjj = 0;
if (aa) // aa != NULL
tmpjj = strlen(aa);
unsigned long tmpqq = size + SAFE_MEM;
size_t tmpii = sizeof (char) * (tmpqq);
aa = (char *) realloc(aa, tmpii);
if (aa == NULL)
raise_error_exit(REALLOC, CHAR_TYPE, fname, lineno);
2000-12-04 15:52:36 +00:00
// do not memset memset(aa, 0, tmpii);
aa[tmpqq-1] = 0;
unsigned long kk = tmpjj;
if (tmpjj > tmpqq)
kk = tmpqq;
for ( ; kk < tmpqq; kk++)
aa[kk] = 0;
call_check(aa, tmpii, fname, lineno);
return aa;
}
</code>
See
2000-11-06 13:19:55 +00:00
<ref id ="Appendix A" name="my_malloc.cpp">.
and the header file
2000-11-06 13:19:55 +00:00
<ref id ="Appendix A" name="my_malloc.h">.
for full implementation of the my_malloc program.
An example on usage of my_malloc and my_free as below:
<code>
char *aa;
int *bb;
float *cc;
aa = (char *) my_malloc(sizeof(char)* 214);
bb = (int *) my_malloc(sizeof(int) * 10);
cc = (float *) my_malloc(sizeof(int) * 20);
aa = my_realloc(aa, sizeof(char) * 34);
bb = my_realloc(bb, sizeof(int) * 14);
cc = my_realloc(cc, sizeof(float) * 10);
</code>
Note that in my_realloc you do not need to cast the datatype as the
variable itself is passed and correct my_realloc is called which
returns the proper datatype pointer. The my_realloc has overloaded
functions for char*, int* and float*.
<!--
*******************************************
************ End of Section ***************
*******************************************
<chapt> Debug files
-->
<sect> Debug files
<p>
To debug any C++ or C programs include the file
2000-11-06 13:19:55 +00:00
<ref id="Appendix A" name="debug.h">
and in your 'Makefile' define DEBUG_STR, DEBUG_PRT, DEBUG_MEM to
turn on the traces from the debug.h functions.
When you remove the '-DDEBUG_STR' etc.. then the debug function calls are set to
((void)0) i.e. NULL,
hence it has no impact on final production release version of project. You can generously
use the debug functions in your programs and it will not increase the size of production
executable.
See the file
2000-11-06 13:19:55 +00:00
<ref id="Appendix A" name="debug.cpp">
for implementation of debug routines.
And see the file
2000-11-06 13:19:55 +00:00
<ref id="Appendix A" name="my_malloc.cpp">
for sample which uses debug.h and debug functions.
See the sample
2000-11-06 13:19:55 +00:00
<ref id="Appendix A" name="Makefile">
.
2000-12-18 15:01:28 +00:00
<!--
*******************************************
************ End of Section ***************
*******************************************
2001-02-13 14:40:24 +00:00
<chapt> IDE tools for C++ <label id="idetools">
-->
<sect> IDE tools for C++ <label id="idetools">
<p>
The following IDE tools (Integrated Development Environment) are available for
C++:
<itemize>
<item> KDE <url name="Kdevelop" url="http://www.kdevelop.org">
<item> Blatura site <url name="C++ Tools" url="http://home.xnet.com/~blatura/linapp6.html#tools">
<item> Amulet <url name="Amulet" url="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/amulet/www">
<item> App Dev suite <url name="Angoss" url="http://www.angoss.com/sw/home.htm">
<item> Make replacement <url name="Brass" url="http://wsd.iitb.fhg.de/~kir/brashome/">
<item> S/W product metrics <url name="CCC" url="http://www.fste.ac.cowan.edu.au/~tlittlef">
<item> Project mgmt, edit, compile, debug <url name="C-Forge" url="http://www.codeforge.com">
<item> Dev environment <url name="Code Crusader" url="http://www.cco.caltech.edu/~jafl/jx/progs.html">
<item> Graphic gdb <url name="Code Medic" url="http://www.cco.caltech.edu/~glenn/medic/">
<item> Code analysis <url name="CodeWizard" url="http://www.parasoft.com/wizard/index.html">
<item> Gen HTML, LaTex for C++ cod <url name="Doc C++" url="http://www.zib.de/Visual/software/doc++/index.html">
<item> GUI toolkit openGL <url name="Ftk" url="http://fltk.easysw.com/">
<item> C++ and Java IDE <url name="GLG IDE" url="http://www.genlogic.com">
<item> HP IDE <url name="HP Eloquence" url="http://www.hp-eloquence.com/sales/info.html">
<item> IDE C++, Java, Pascal <url name="RHIDE" url="http://www.tu-chemnitz.de/~sho/rho/rhide.html">
<item> IDE for C++, Java <url name="SNiff" url="http://www.takefive.com/">
<item> IDE for C++, Java <url name="Wipeout" url="http://www.softwarebuero.de/wipeout-eng.html">
<item> X-based dev env <url name="XWPE" url="http://www.rpi.edu/~payned/xwpe">
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2001-01-02 15:55:26 +00:00
<chapt> C++ Online Textbooks and Docs <label id="onlinebooks">
2000-12-18 15:01:28 +00:00
-->
2001-01-02 15:55:26 +00:00
<sect> C++ Online Textbooks and Docs <label id="onlinebooks">
2000-12-18 15:01:28 +00:00
<p>
<itemize>
<item> "C++ Annotations" online book
main site:<url url="http://www.icce.rug.nl/docs/cplusplus">
better site : <url url="http://www.physik.tu-muenchen.de/cip-tutorials/Documents/c++-annotations/cplusplus.html">
<item>"Teach Yourself C++ in 21 days" online textbook <url url="http://guides.oernii.sk/c++/index.htm">
<item>"C++ Online" Textbook <url url="http://www.bruceeckel.com/DownloadSites">
<item> C++ Open books: <url url="http://www.softpanorama.org/Bookshelf/cpp.shtml"> and
click on Open Books.
<item> "Who's Afraid of C++?" online textbook <url url="http://www.steveheller.com/whos">
2001-01-12 14:53:07 +00:00
<item> "Introduction to Object Oriented Programming" an ebook <url url="http://www.gnacademy.org/uu-gna/text/cc/Tutorial/tutorial.html">
2000-12-18 15:01:28 +00:00
<p>
<item>Porting C++ to Java <url url="http://www.ibm.com/java/education/portingc">
<item>C/C++ Journals <url url="http://www.math.utah.edu/pub/tex/bib/toc/cccuj.html">
<item>Yahoo C++ category site <url url="http://dir.yahoo.com/Computers_and_Internet/Programming_Languages/C_and_C__/C__">
<item>C Library Reference Guide<url url="http://www.acm.uiuc.edu/webmonkeys/book/c_guide/index.html">
2001-01-02 15:55:26 +00:00
<item> Online textbooks C++/Java <url url="http://www.informit.com/free_library">
</itemize>
Java books which will be useful for C++ programmers:
<itemize>
<item> Great Web reference site <url url="http://www.webreference.com/index2.html">
<item> Many java books <url url="http://freewarejava.com/books/index.shtml">
<item> Intro to Java V3.0 <url url="http://math.hws.edu/javanotes">
mirror <url url="http://matrix.mvhs.fuhsd.org/~deruiter/javanotes3/contents.html">
<item> Web Library: <url url="http://www.itlibrary.com">
<item> Intermediate Level Java book: <url url="http://www.bruceeckel.com">
<item> Thinking in Java : <url url="http://www.sce.carleton.ca/netmanage/java/thinking/toc.html">
<item> John Hopkins Univ - Java resources <url url="http://www.apl.jhu.edu/~hall/java">
<item> online java tutorial <url url="http://chortle.ccsu.ctstateu.edu/cs151/cs151java.html">
<item> Practical guide for Java <url url="http://java.sun.com/docs/books/tutorial/index.html">
<item> Java <url url="http://journals.ecs.soton.ac.uk/java/tutorial/TOC.html">
2000-12-18 15:01:28 +00:00
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
<chapt> C++ Coding Standards
-->
<sect> C++ Coding Standards
<p>
2000-12-23 00:32:23 +00:00
Coding standard is very essential for readability and maitainence of programs. And
it also greatly inproves the productivity of the programmer. The GNU
C++ compiler <bf>must enforce</bf> coding discipline. The following is suggested -
inside class definition:
2000-12-18 15:01:28 +00:00
<itemize>
2000-12-23 00:32:23 +00:00
<item> All public variables must begin with <bf>m</bf> like <bf>mFooVar</bf>.
The <bf>m</bf> stands for <it>member</it>.
<item> All protected variables must begin with <bf>mt</bf>,
like <bf>mtFooVar</bf> and methods with t, like <bf>tFooNum()</bf>.
The <bf>t</bf> stands for <it>protected</it>.
<item> All private variables must begin with <bf>mv</bf>, like <bf>mvFooVar</bf> and
methods with v, like <bf>vFooLone()</bf>. The <bf>v</bf> stands for <it>private</it>.
<item> All public, protected and private variables must begin with
uppercase after <bf>m</bf> like F in <bf>mFooVar</bf>.
2000-12-18 15:01:28 +00:00
<item> All pointer variables must be prefixed with p, like
<itemize>
2000-12-23 00:32:23 +00:00
<item>Public variables <bf>mpFooVar</bf> and methods like FooNum()
<item>Protected variables <bf>mtpFooVar</bf> and methods with t like tFooNum()
<item>Private variables <bf>mvpFooVar</bf> and methods with v like vFooNum()
2000-12-18 15:01:28 +00:00
</itemize>
</itemize>
2000-12-23 00:32:23 +00:00
The compiler should generate error if the code does not follow above standard.
2000-12-18 15:01:28 +00:00
The C++ compiler can provide a flag option to bypass strict coding standard to compile
old source code, and for all new code being developed will follow the
uniform world-wide coding standard.
2000-12-23 00:32:23 +00:00
In the sample code given below <bf>t</bf> stands for <bf>protected</bf>,
2000-12-18 15:01:28 +00:00
<bf>v</bf> stands for <bf>private</bf>,
<bf>m</bf> stands for <bf>member-variable</bf> and
<bf>p</bf> stands for <bf>pointer</bf>.
<code>
2000-12-23 00:32:23 +00:00
class SomeFunMuncho
2000-12-18 15:01:28 +00:00
{
public:
2000-12-23 00:32:23 +00:00
int mTempZimboniMacho; // Only temporary variables should be public as per OOP
float *mpTempArrayNumbers;
2000-12-18 15:01:28 +00:00
int HandleError();
2000-12-23 00:32:23 +00:00
float getBonyBox(); // Public accessor as per OOP design
float setBonyBox(); // Public accessor as per OOP design
2000-12-18 15:01:28 +00:00
protected:
float mtBonyBox;
int *mtpBonyHands;
char *tHandsFull();
int tGetNumbers();
private:
float mvJustDoIt;
char mvFirstName[30];
int *mvpTotalValue;
char *vSubmitBars();
int vGetNumbers();
};
</code>
2000-12-23 00:32:23 +00:00
When your program grows by millions of lines of code, then you will greatly
appreciate the naming convention as above. The readability of code improves,
because just by looking at the variable name like <bf>mvFirstName</bf> you can
tell that it is member of a class and is a private variable.
2000-12-18 15:01:28 +00:00
Visit the C++ Coding Standards URLs
<itemize>
<item> C++ FAQ Lite - Coding standards <url url="http://new-brunswick.net/workshop/c++/faq/coding-standards.html">
2000-12-23 00:32:23 +00:00
<item> Rice university coding standard <url url="http://www.cs.rice.edu/~dwallach/CPlusPlusStyle.html">
<item> Identifiers to avoid in C++ Programs <url url="http://oakroadsystems.com/tech/cppredef.htm">
2000-12-18 15:01:28 +00:00
<item> Coding standards from Possibility <url url="http://www.possibility.com/Cpp/CppCodingStandard.html">
2000-12-23 00:32:23 +00:00
and <url name="mirror site" url="http://www.cs.umd.edu/users/cml/cstyle/CppCodingStandard.html">
<item> Coding standards for Java and C++ from Ambysoft <url url="http://www.ambysoft.com/javaCodingStandards.html">
2000-12-18 15:01:28 +00:00
<item> Rules and recommendations <url url="http://www.cs.umd.edu/users/cml/cstyle/">
<item> Indent and annotate <url url="http://www.cs.umd.edu/users/cml/cstyle/indhill-annot.html">
<item> Elemental rules <url url="http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules.html">
<item> C++ style doc <url url="http://www.cs.umd.edu/users/cml/cstyle/Wildfire-C++Style.html">
2000-12-23 00:32:23 +00:00
<item> C++ Coding Standards by Brett Scolcum <url url="http://www.skypoint.com/~slocum/prog/cppstds.html">
<item> Logikos C++ Coding Standards <url url="http://www.logikos.com/standards/cpp_std.html">
<item> NRad C++ coding standards <url url="http://cadswes.colorado.edu/~billo/standards/nrad">
<item> BEJUG C++ coding standards <url url="http://www.meurrens.org/ip-Links/java/joodcs/ToddHoff.html">
<p>
See also
<item> For rapid navigation with ctags
<url name="Vim color text editor" url="http://metalab.unc.edu/LDP/HOWTO/Vim-HOWTO.html">
<item> To improve productivity see <url name="C++ Beautifier HOWTO" url="http://metalab.unc.edu/LDP/HOWTO/C-C++Beautifier-HOWTO.html">
2000-12-18 15:01:28 +00:00
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-12-18 15:01:28 +00:00
<chapt> C++ Online Docs
-->
2000-12-18 15:01:28 +00:00
<sect> C++ Online Docs
<p>
2000-10-30 15:40:21 +00:00
There are <bf>MORE THAN ONE MILLION</bf> online articles/textbooks/reference
2000-12-04 15:52:36 +00:00
guides on C++ language. That is because C++ is used extensively for a very long
2000-10-09 16:27:45 +00:00
period of time.
You can find them using the Internet search engines like Yahoo, Lycos, Excite etc..
Visit the following C++ sites :-
2000-12-18 15:01:28 +00:00
<itemize>
2000-10-09 16:27:45 +00:00
<item>C++ STL basic string class <url url="http://www.sgi.com/Technology/STL/basic_string.html">
2000-11-13 15:38:38 +00:00
<item> See the section <ref id="stlref" name="STL References">
2000-10-30 15:40:21 +00:00
<p>
<item>C++ Crash-proof site <url url="http://www.troubleshooters.com/codecorn/crashprf.htm">
<item>C++ Memory site<url url="http://www.troubleshooters.com/codecorn/memleak.htm">
2000-10-30 15:40:21 +00:00
<p>
2000-10-16 14:54:12 +00:00
<item>GNU Main site <url url="http://www.gnu.org"> and gnu C++ site at
<url url="http://www.gnu.org/software/gcc/gcc.html">
2000-10-09 16:27:45 +00:00
<item>GNU C++ Library - socs <url url="http://www.socs.uts.edu.au/doc/gnuinfo/libg++/libg++_18.html">
<item>GNU C++ Library - gsi <url url="http://www.gsi.de/doc/gnu/libg++_toc.html">
<item>GNU C++ Library - techno <url url="http://www.techno.spb.ru/~xbatob/FAQ/GNU/libg++_toc.html">
<item>GNU C++ Library - utah <url url="http://www.math.utah.edu/docs/info/libg++_toc.html">
<item>AS University C++ Standard String class <url url="http://www.eas.asu.edu/~cse200/outline">
2000-10-30 15:40:21 +00:00
<p>
2000-10-09 16:27:45 +00:00
<item>Java JString for C++ <url url="http://www.mike95.com/c_plusplus/classes/JString/JString_cpp.asp">
<item>C++ Language Reference <url url="http://www.msoe.edu/~tritt/cpplang.html">
<item>C++ Program examples and samples <url url="http://www.msoe.edu/~tritt/cpp/examples.html">
<item>Neil's C++ stuff <url url="http://www.cyclone7.com/cpp">
</itemize>
Internet has vast amounts of documentation on C++. Visit the search engines
like Yahoo, Lycos, Infoseek, Excite. Type in the
keywords
<bf>'C++ tutorials'</bf>
<bf>'C++ references'</bf>
<bf>'C++ books'</bf>
. You can narrow down the search criteria by clicking on <it>Advanced</it>
search and select <it>search by exact phrase</it>
<itemize>
<item> <url url="http://www.yahoo.com">
<item> <url url="http://www.lycos.com">
<item> <url url="http://www.infoseek.com">
<item> <url url="http://www.excite.com">
<item> <url url="http://www.mamma.com">
</itemize>
<sect1> C++ Tutorials
<p>
There are many on-line tutorials available on internet. Type 'C++ tutorials'
in the search engine.
2000-10-09 16:27:45 +00:00
<itemize>
<item>C++ Tutorial <url url="http://www.xploiter.com/programming/c/index.shtml">
<item>C++ Tutorial IISc, India <url url="http://www.csa.iisc.ernet.in/Documentation/Tutorials/StyleGuides/c++-style.html">
<item>C++ Tutorial Brown Univ <url url="http://wilma.cs.brown.edu/courses/cs032/resources/C++tutorial.html">
<item>C++ Tutorial <url url="http://home.msuiit.edu.ph/~ddd/tutorials/cpp/cpplist.htm">
<item>C++ Tutorial IOstreams <url url="http://osiris.sunderland.ac.uk/~cs0pdu/pub/com365/Sched3/iocpp.html">
</itemize>
2000-12-18 15:01:28 +00:00
<sect1> Useful links
<p>
2000-12-18 15:01:28 +00:00
Bird's eye view of C++ URLs (about 153 url links)
<url url="http://www.enteract.com/~bradapp/links/cplusplus-links.html">
2000-12-18 15:01:28 +00:00
This <url url="URL: http://www.snippets.org">
portable C code contains over 360 files.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect1> C++ Quick-Reference
<p>
Type 'C++ Reference' in the search engine.
2000-10-09 16:27:45 +00:00
<itemize>
<item>C++ quick ref <url url="http://www.cs.jcu.edu.au/~david/C++SYNTAX.html">
<item>C++ Standard Library Quick Reference <url url="http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html">
<item>C++ STL from halper <url url="http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html">
</itemize>
<sect1> C++ Usenet Newsgroups
<p>
<itemize>
2000-12-04 15:52:36 +00:00
<item> C++ newsgroups :
<htmlurl url="news:comp.lang.c++.announce"
name="comp.lang.c++.announce">
<item> C++ newsgroups :
<htmlurl url="news:comp.lang.c++.*"
name="comp.lang.c++.*">
<item> C++ newsgroups : <url url="http://marshall-cline.home.att.net/cpp-faq-lite">
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
<chapt change> Memory Tools
-->
<sect> Memory Tools
<p>
Use the following memory debugging tools
<itemize>
2001-03-17 15:32:41 +00:00
<item> The <bf>MPatrol</bf> is a very powerful memory debugging tool.
It is at <url url="http://www.cbmamiga.demon.co.uk/mpatrol">
and at <url url="http://www.rpmfind.net"> go here and search mpatrol.
If you are using linux then you must download the mpatrol*.src.rpm file from the
rpmfind.net. To update the mpatrol*.src.rpm to latest version, you can use the
old mpatrol.spec file and latest mpatrol*.tar.gz file to rebuild new *.src.rpm.
<item> On linux contrib cdrom see mem_test*.rpm package
2001-03-17 15:32:41 +00:00
and at <url url="http://www.rpmfind.net"> go here and search mem_test.
<item> On linux cdrom see ElectricFence*.rpm package
2001-03-17 15:32:41 +00:00
and at <url url="http://www.rpmfind.net"> go here and search electricfence.
<item> Purify Tool from Rational Software Corp <url url="http://www.rational.com">
<item> Insure++ Tool from Parasoft Corp <url url="http://www.parasoft.com">
<item> Linux Tools at <url url="http://www.xnet.com/~blatura/linapp6.html#tools">
<item> Search the Internet engines like Yahoo, Lycos, Excite, Mamma.com
for keyword "Linux memory debugging tools".
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
<chapt change> Related URLs
-->
<sect> Related URLs
<p>
2000-07-10 14:17:49 +00:00
You MUST use a color editor like 'Vim' (Vi improved) while coding in C++. Color
editors greatly increase your productivity. Visit the URL for Vim howto below.
Visit following locators which are related to C, C++ -
<itemize>
<item> Vim color text editor for C++, C <url url="http://metalab.unc.edu/LDP/HOWTO/Vim-HOWTO.html">
<item> C++ Beautifier HOWTO <url url="http://metalab.unc.edu/LDP/HOWTO/C-C++Beautifier-HOWTO.html">
2000-08-03 18:24:33 +00:00
<item> Source code control system for C++ programs (CVS HOWTO) <url url="http://metalab.unc.edu/LDP/HOWTO/CVS-HOWTO.html">
2001-02-01 14:40:35 +00:00
<item> Linux goodies <url url="http://www.aldev.8m.com">
and mirrors at
<url url="http://aldev.webjump.com" name="webjump">,
<url url="http://www.angelfire.com/nv/aldev" name="angelfire">,
<url url="http://www.geocities.com/alavoor/index.html" name="geocities">,
<url url="http://aldev.virtualave.net" name="virtualave">,
<url url="http://aldev.bizland.com" name="bizland">,
<url url="http://members.theglobe.com/aldev/index.html" name="theglobe">,
<url url="http://members.spree.com/technology/aldev" name="spree">,
<url url="http://homepages.infoseek.com/~aldev1/index.html" name="infoseek">,
<url url="http://www3.bcity.com/aldev" name="bcity">,
<url url="http://aldev.50megs.com" name="50megs">
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2001-02-01 14:40:35 +00:00
<chapt> PIKE (C++ Scripting Language)
-->
<sect> PIKE (C++ Scripting Language)
<p>
The major disadvantage of C++ is that you must recompile and link the
object files to create a executable anytime you make a small change.
The scripting language like PIKE eliminates the linking and re-compiling
and will really speed up the development process.
2001-02-13 14:40:24 +00:00
As memory (RAM) prices are dropping and CPU speeds
are increasing, scripting language like PIKE will
2001-02-01 14:40:35 +00:00
<bf>EXPLODE in popularity</bf>. PIKE will become most widely used
scripting language as it is object oriented and it's syntax is very identical to
that of C++ language.
2001-02-13 14:40:24 +00:00
Programming productivity will increase by <bf>five times</bf> by using the
Pike C++ scripting language. And Pike is very useful for 'proof of concept'
and developing prototypes rapidly.
2001-02-01 14:40:35 +00:00
The Pike is at <url url="http://pike.roxen.com">
2001-02-24 15:51:34 +00:00
and at <url url="http://www.roxen.com">.
The Roxen Web server is completely written in Pike, which demonstrates how
powerful Pike is. Pike runs much faster than Java for some operations
and is quite efficient in using memory resources.
2001-02-01 14:40:35 +00:00
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-12-18 15:01:28 +00:00
<chapt change> Templates
-->
<sect> Templates
<p>
<itemize>
<item> <url url="http://babbage.cs.qc.edu/STL_Docs/templates.htm">
Mirror at: <url url="http://www.mike95.com/c_plusplus/tutorial/templates">
<p>
<item> This tells about #pragma template : -
<url url="http://www.dgp.toronto.edu/people/JamesStewart/270/9697f/notes/Nov25-tut.html">
<p>
2000-12-23 00:32:23 +00:00
<item> Very GOOD site:
2000-12-18 15:01:28 +00:00
<url url="http://www.cplusplus.com/doc/tutorial/tut5-1.html">
<url url="http://www.cplusplus.com/doc/tutorial">
<p>
2000-12-23 00:32:23 +00:00
<item> For certification of C++: goto <url url="http://examware.com"> and click on "Tutorials" and then C/C++ button
2000-12-18 15:01:28 +00:00
<p>
<item> C++ Open books: <url url="http://www.softpanorama.org/Lang/cpp.shtml">
and click on tutorials
<p>
<item> Templates tutorial : <url url="http://www.infosys.tuwien.ac.at/Research/Component/tutorial/prwmain.htm">
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-13 15:38:38 +00:00
<chapt> STL References <label id="stlref">
-->
<sect> STL References <label id="stlref">
<p>
Please visit the following sites for STL -
<itemize>
<item> Very good intro to iterators
<url url="http://www.cs.trinity.edu/~joldham/1321/lectures/iterators/">
<item> CMU univ <url url="http://www.cs.cmu.edu/afs/andrew/course/15/129/Cpp/10-STL/">
<item> Intro to STL SGI
<url url="http://www.sgi.com/Technology/STL/stl_introduction.html">
<item> Mumits STL Newbie guide
<url url="http://www.xraylith.wisc.edu/~khan/software/stl/STL.newbie.html">
Mumit Khan's informative STL introduction is full of examples
<url url="http://abel.hive.no/C++/STL/stlnew.html">
<item> ObjectSpace examples: ObjectSpace has contributed over 300 examples to the public domain and these are a very good start for beginners.
<url url="ftp://butler.hpl.hp.com/stl/examples.zip">
<item> Joseph Y. Laurino's STL page.
<url url="http://weber.u.washington.edu/~bytewave/bytewave_stl.html">
<item> Musser's STL docs and examples. Very nice.
<url url="http://www.cs.rpi.edu/~musser/stl.html">
<item> STL Newbie home site.
<url url="http://www.xraylith.wisc.edu/~khan/software/stl/STL.newbie.html">
<item> Marian Corcoran's STL FAQ.
<url url="ftp://butler.hpl.hp.com/stl/stl.faq">
</itemize>
STL Tutorial:
<itemize>
<item> The best doc on tutorial - <url url="http://www.decompile.com/html/tut.html">
Mirror: <url url="http://mip.ups-tlse.fr/~grundman/stl-tutorial/tutorial.html">
<item> very good - <url url="http://www.yrl.co.uk/~phil/stl/stl.htmlx">
<item> C++ Standard Template LibraryAnother great tutorial, by Mark Sebern
<url url="http://www.msoe.edu/eecs/cese/resources/stl/index.htm">
<item> By Jak Kirman:
<url url="http://129.187.112.56/Misc/Computer/stl-tutorial/tutorial_9.html">
Mirrors : <url url="http://www.cs.brown.edu/people/jak/proglang/cpp/stltut/tut.html">
<url url="http://saturn.math.uaa.alaska.edu/~afjhj/cs403/stl/tutorial.html">
<item> Technical University Vienna by Johannes Weidl <url url="http://dnaugler.cs.semo.edu/tutorials/stl">
mirror <url url="http://www.infosys.tuwien.ac.at/Research/Component/tutorial/prwmain.htm">
<item> Colorful Tutorial <url url="http://www.codeproject.com/cpp/stlintroduction.asp">
</itemize>
Ready-made Components for use with the STL
<itemize>
<item> STL components Collected by Boris Fomitche
<url url="http://www.metabyte.com/~fbp/stl/components.html">
</itemize>
Main STL sites -
<itemize>
<item>C++ STL from SGI <url url="http://www.sgi.com/Technology/STL">
<item>C++ STL from RPI univ <url url="http://www.cs.rpi.edu/projects/STL/htdocs/stl.html">
<item>Lycos C++ STL site <url url="http://dir.lycos.com/Computers/Programming/Languages/C%2B%2B/Class_Libraries/STL">
<item>STL for C++ Programmers <url url="http://userwww.econ.hvu.nl/~ammeraal/stlcpp.html">
<item>C++ STL from halper <url url="http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html">
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
2000-11-13 15:38:38 +00:00
<sect1> Overview of the STL
<p>
2000-11-06 13:19:55 +00:00
The STL offers the programmer a number of useful data structures and algorithms. It is made up the following components.
<itemize>
2000-11-06 13:19:55 +00:00
<item> Containers. There are two types:
<itemize>
<item> Sequential. This group comprises the vector, list and dequeue types.
<item> Sorted Associative. This group comprises the set, map, multiset and multimap types.
</itemize>
<p>
<item> Iterators. These are pointer like objects that allow the user to step through the contents of a container.
<p>
<item> Generic Algorithms. The STL provides a wide range of efficently implemented standard algorithms (for example find, sort
and merge) that work with the container types. (Some of the containers have special purpose implementations of these
algorithms as member functions.)
<p>
<item> Function Objects. A function object is an instance of a class that provides a definition of operator(). This means that you can
use such an object like a function.
<p>
<item> Adaptors. The STL provides
<itemize>
<item> Container adaptors that allow the user to use, say, a vector as the basis of a stack.
<item> Function adaptors that allow the user to construct new function objects from existing function objects.
</itemize>
<p>
<item> Allocators. Every STL container class uses an Allocator class to hold information about the memory model the program is
using. I shall totally ignore this aspect of the STL.
</itemize>
2000-11-06 13:19:55 +00:00
I will be considering the use of the vector, list, set and map containers. To make use of these containers you have to be able to use
iterators so I shall have something to say about STL iterators. Using the set and map containers can mean having to supply a
simple function object to the instantiation so I shall also have something to say about function objects. I will only briefly mention
the algorithms supplied by the STL. I will not mention adaptors at all.
I have taken liberties with some of the types of function arguments -- for example most of the integer arguments referred to in
what follows actually have type size_type which is typedef'ed to an appropriate basic type depending on the allocation model being
used. If you want to see the true signatures of the various functions discussed have a look at the Working Paper or the header
files.
There are a number of utility classes supplied with the STL. The only one of importance to us is the pair class. This has the
following definition:
2000-07-05 17:23:44 +00:00
<code>
2000-11-06 13:19:55 +00:00
template<class T1, class T2>
class pair {
public:
T1 first;
T2 second;
pair(const T1& a, const T2& b) : first(a), second(b) {}
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
};
</code>
2000-11-06 13:19:55 +00:00
and there is a convenient function make_pair with signature:
2000-11-06 13:19:55 +00:00
<code>
pair<T1,T2> make_pair(const T1& f, const T2&,s)
</code>
2000-11-06 13:19:55 +00:00
as well as implementations of operator== and operator &lt . There is nothing complicated about this template class and you should be
able to use it without further guidance. To use it #include the header file pair.h. It crops up in a number of places but particularly
when using the set and map classes.
<sect1> Header Files
<p>
To use the various bits of the STL you have to #include the appropriate header files. These may differ slightly from compiler to
compiler but for g++ the ones of interest are:
2000-07-05 17:23:44 +00:00
<itemize>
2000-11-06 13:19:55 +00:00
<item> <it>vector.h</it> for the vector type.
<item> <it>list.h</it> for the list type.
<item> <it>set.h</it> for the set type.
<item> <it>map.h</it> for the map type.
<item> <it>algo.h</it> for access to the generic algorithms.
</itemize>
2000-11-06 13:19:55 +00:00
If you don't want to remember which is which you could just use stl.h which includes all the above (and all the other header files of
the STL as well).
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
-->
<sect1> The Container Classes Interface
<p>
The container classes have many member functions that have the same names. These functions provide the same (or very similar)
services for each of the classes (though, of course, the implementations will be different). The following table lists the functions
that we shall consider in more detail. A star opposite a function name indicates that the container type heading the column
provides a member function of that name.
<!--
another option is use <table>
<simplelist type="horiz" columns="2">
<member>a</member>
<member>a</member>
<member>a</member>
<member>a</member>
<member>a</member>
<member>a</member>
<member>a</member>
</simplelist>
2000-11-13 15:38:38 +00:00
<table loc=p>
<tabular ca="rll">
Line No.<colsep>Country <colsep>Capital <rowsep><hline>
1 <colsep>Norway <colsep>Oslo <rowsep>
2 <colsep>Japan <colsep>Tokyo <rowsep>
3 <colsep>Finland <colsep>Helsinki <rowsep>
</tabular>
<caption><bf>Some capitals</bf></caption>
</table>
2000-11-06 13:19:55 +00:00
-->
2000-11-13 15:38:38 +00:00
<!-- Put a line space after &lowbar below to avoid space between.... -->
<table loc=p>
<tabular ca="rll">
Operation <colsep>Purpose <colsep>Vector <colsep>List <colsep>Set <colsep>Map <rowsep><hline>
== <colsep>comparison <colsep>* <colsep>*<colsep>*<colsep>*<rowsep>
&lt<colsep> comparison<colsep> *<colsep> *<colsep> *<colsep> *<rowsep>
begin<colsep> iterator<colsep> *<colsep> *<colsep> *<colsep> *<colsep><rowsep>
end<colsep> iterator<colsep> *<colsep> *<colsep> *<colsep> *<rowsep>
size<colsep> no. of elements<colsep> *<colsep> *<colsep> *<colsep> *<rowsep>
empty<colsep> is container empty<colsep> *<colsep> *<colsep> *<colsep> *<rowsep>
front<colsep> first element<colsep> *<colsep> * <rowsep>
back<colsep> last element<colsep> *<colsep> * <rowsep>
&lsqb &rsqb <colsep> element access/modification<colsep> *<colsep> <colsep> <colsep>*<colsep><rowsep>
insert<colsep> insert element(s)<colsep> *<colsep> *<colsep> *<colsep> *<rowsep>
push&lowbar
back<colsep> insert new last element<colsep> *<colsep> *<colsep> <rowsep>
push&lowbar
front<colsep> insert new first element<colsep> <colsep>*<colsep> <rowsep>
erase<colsep> remove element(s)<colsep> *<colsep> *<colsep> *<colsep> *<rowsep>
pop&lowbar
back<colsep> remove last element<colsep> *<colsep> *<colsep> <rowsep>
pop&lowbar
front<colsep> remove last element<colsep> <colsep>*<colsep> <rowsep>
</tabular>
<caption><bf>Container Class Interface</bf></caption>
</table>
<!--
2000-11-06 13:19:55 +00:00
<code>
Operation Purpose Vector List Set Map
== comparison * * * *
&lt comparison * * * *
begin iterator * * * *
end iterator * * * *
size no. of elements * * * *
empty is container empty * * * *
front first element * *
back last element * *
[] element access/modification * *
insert insert element(s) * * * *
push_back insert new last element * *
push_front insert new first element *
erase remove element(s) * * * *
pop_back remove last element * *
pop_front remove last element *
</code>
2000-11-13 15:38:38 +00:00
-->
2000-11-06 13:19:55 +00:00
If the following discussion leaves something unclear
(and it will) you can always write a small test program to investigate how
some function or feature behaves.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
2000-11-06 13:19:55 +00:00
<sect1> Vectors
<p>
2000-11-06 13:19:55 +00:00
A vector is an array like container that improves on the C++ array types. In particular it is not neccessary to know how big you
want the vector to be when you declare it, you can add new elements to the end of a vector using the <bf><it>push_back</it></bf> function. (In fact the
<bf><it>insert</it></bf> function allows you insert new elements at any position of the vector, but this is a very inefficent operation -- if you need to
do this often consider using a list instead).
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
2000-11-06 13:19:55 +00:00
<sect2> Constructing Vectors
<p>
2000-11-06 13:19:55 +00:00
<it>vector</it> is a class template so that when declaring a vector object you have to state the type of the objects the vector is to contain. For
example the following code fragment
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
vector<int> v1;
vector<string> v2;
vector<FiniteAutomaton> v3;
</code>
2000-10-09 16:27:45 +00:00
2000-11-06 13:19:55 +00:00
declares that v1 is a vector that holds integers, v2 a vector that holds strings and v3 holds objects of type FiniteAutomaton
2001-01-12 14:53:07 +00:00
(presumably an user defined class type). These declarations do not say anything about how large the vectors are to be
2000-11-06 13:19:55 +00:00
(implementations will use a default starting size) and you can grow them to as large as you require.
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
You can give an inital size to a vector by using a declaration like
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
<code>
vector<char> v4(26);
</code>
2000-11-06 13:19:55 +00:00
which says that v4 is to be vector of characters that initially has room for 26 characters. There is also a way to initailise a vector's
elements. The declaration
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
<code>
vector<float> v5(100,1.0);
</code>
2000-11-06 13:19:55 +00:00
says that <it>v5</it> is a vector of 100 floating point numbers each of which has been initialised to 1.0.
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
-->
<sect2> Checking Up on Your Vector
<p>
Once you have created a vector you can find out the current number of elements it contains by using the <it>size</it> function. This
function takes no arguments and returns an integer (strictly a value of type <it>size_type</it>,
but this gets converted to an integer) which
says how many elements there are in the vector. What will be printed out by the following small program?
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
<vector-size.cc>=
#include <iostream.h>
#include <vector.h>
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
void main()
2000-08-03 18:24:33 +00:00
{
2000-11-06 13:19:55 +00:00
vector<int> v1;
vector<int> v2(10);
vector<int> v3(10,7);
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
cout << "v1.size() returns " << v1.size() << endl;
cout << "v2.size() returns " << v2.size() << endl;
cout << "v3.size() returns " << v3.size() << endl;
2000-08-03 18:24:33 +00:00
}
2000-11-06 13:19:55 +00:00
</code>
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
To check on wether your vector is empty or not you can use the empty function. This takes no arguments and returns a boolean
value, true if the vector is empty, false if it is not empty. What will be printed out by the following small program (true prints as 1
and false prints as 0)?
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
<vector-empty.cc>=
#include <iostream.h>
#include <vector.h>
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
void main()
2000-08-03 18:24:33 +00:00
{
2000-11-06 13:19:55 +00:00
vector<int> v1;
vector<int> v2(10);
vector<int> v3(10,7);
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
cout << "v1.empty() has value " << v1.empty() << endl;
cout << "v2.empty() has value " << v2.empty() << endl;
cout << "v3.empty() has value " << v3.empty() << endl;
}
</code>
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
2000-11-06 13:19:55 +00:00
<sect2> Accessing Elements of a Vector
<p>
2000-11-06 13:19:55 +00:00
You can access a vector's elements using operator[]. Thus, if you wanted to print out all the elements in a vector you could use code
like
<code>
2000-11-06 13:19:55 +00:00
vector<int> v;
// ...
for (int i=0; i<v.size(); i++)
cout << v[i];
</code>
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
(which is very similar to what you might write for a builtin array).
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
You can also use operator[] to set the values of the elements of a vector.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
vector<int> v;
// ...
for (int i=0; i<v.size(); i++)
v[i] = 2*i;
</code>
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
The function front gives access to the first element of the vector.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
vector<char> v(10,'a');
// ...
char ch = v.front();
</code>
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
You can also change the first element using front.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
vector<char> v(10,'a');
// ...
v.front() = 'b';
</code>
The function back works the same as front but for the last element of the vector.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
vector<char> v(10,'z');
// ...
char last = v.back();
v.back() = 'a';
</code>
2000-11-06 13:19:55 +00:00
Here is a simple example of the use of [].
<code>
<vector-access.cc>=
#include <vector.h>
#include <iostream.h>
void main()
{
vector<int> v1(5);
int x;
cout << "Enter 5 integers (seperated by spaces):" << endl;
for (int i=0; i<5; i++)
cin >> v1[i];
cout << "You entered:" << endl;
for (int i=0; i<5; i++)
cout << v1[i] << ' ';
cout << endl;
}
</code>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
-->
<sect2> Inserting and Erasing Vector Elements
<p>
Along with operator[] as described above there are a number of other ways to change or access the elements in a vector.
2000-11-06 13:19:55 +00:00
<itemize>
<item>push_back will add a new element to the end of a vector.
<item>pop_back will remove the last element of a vector.
<item>insert will insert one or more new elements, at a designated position, in the vector.
<item>erase will remove one or more elements from a vector between designated positions.
</itemize>
2000-11-06 13:19:55 +00:00
Note that insert and erase are expensive operations on vectors. If you use them a lot then you should consider using the list data
structure for which they are more efficient.
<code>
2000-11-06 13:19:55 +00:00
<vector-mod.cc>=
#include <iostream.h>
#include <vector.h>
2000-11-06 13:19:55 +00:00
void main()
{
vector<int> v;
2000-11-06 13:19:55 +00:00
for (int i=0; i<10; i++) v.push_back(i);
cout << "Vector initialised to:" << endl;
for (int i=0; i<10; i++) cout << v[i] << ' ' ;
cout << endl;
2000-11-06 13:19:55 +00:00
for (int i=0; i<3; i++) v.pop_back();
cout << "Vector length now: " << v.size() << endl;
cout << "It contains:" << endl;
for (int i=0; i<v.size(); i++) cout << v[i] << ' ';
cout << endl;
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
int a1[5];
for (int i=0; i<5; i++) a1[i] = 100;
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
v.insert(& v[3], & a1[0],& a1[3]);
cout << "Vector now contains:" << endl;
for (int i=0; i<v.size(); i++) cout << v[i] << ' ';
cout << endl;
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
v.erase(& v[4],& v[7]);
cout << "Vector now contains:" << endl;
for (int i=0; i<v.size(); i++) cout << v[i] << ' ';
cout << endl;
2000-07-05 17:23:44 +00:00
}
2000-11-06 13:19:55 +00:00
</code>
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
In the above a vector v has been declared then initialised using push_back. Then some elements have been trimmed off it's end using
pop_back. Next an ordinary integer array has been created and then some of its elements inserted into v using insert. Finally erase
has been used to remove elements from v. The functions used above take arguments as follows.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<itemize>
<item> push_back takes a single argument of the type of the elements held in the vector.
<item> pop_back takes no arguments. It is a mistake to use pop_back on an empty vector.
<item> insert has three forms:
<itemize>
<item>insert(pos, T& x) which will insert the single element x at position pos in the vector.
<item>insert(pos, start, end) which inserts a sequence of elements from some other container at position pos in the vector. The
<item>sequence of elements is identified as starting at the start element and continuing to, but not including, the end element.
<item>insert(pos, int rep, T& x) inserts rep copies of x at position pos in the vector.
</itemize>
</itemize>
As indicated in the code above the position pos should be the address of the element to insert at, whilst the start and end
arguments are likewise also addresses. (The true story is that they are iterators -- see next subsection and following
section).
<itemize>
<item> erase has two forms (pos, start and end have the same types as for the insert function):
<itemize>
<item> erase(pos) which will remove the element at position pos in the vector.
<item> insert(start,end) which will remove elements starting at postion start upto, but not including, the element at position end.
</itemize>
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
-->
<sect2> Vector Iterators
<p>
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
The simple way to step through the elements of a vector v is as we have done above:
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
<code>
for (int i=0; i<v.size(); i++) { ... v[i] ... }
</code>
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
Another way is to use iterators. An iterator can be thought of as a pointer into the container, incrementing the iterator allows you
to step through the container. For container types other than vectors iterators are the only way to step through the container.
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
For a vector containing elements of type T:
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
<code>
vector<T> v;
</code>
2000-11-06 13:19:55 +00:00
an iterator is declared as follows:
2000-11-06 13:19:55 +00:00
<code>
vector<T>::iterator i;
</code>
2000-11-06 13:19:55 +00:00
Such iterators are constructed and returned by the functions begin() and end(). You can compare two iterators (of the same type)
using == and !=, increment using ++ and dereference using *. [In fact vector iterators allow more operations on them - see next
section for more information].
2000-11-06 13:19:55 +00:00
Here is an illustration of how to use iterators with vectors.
2000-11-06 13:19:55 +00:00
<code>
<vector-iterator.cc>=
#include <iostream.h>
#include <vector.h>
2000-11-06 13:19:55 +00:00
void main()
{
2000-11-06 13:19:55 +00:00
vector<int> v(10);
first is ``less'' than the second
2000-11-06 13:19:55 +00:00
int j = 1;
2000-11-06 13:19:55 +00:00
vector<int>::iterator i;
2000-11-06 13:19:55 +00:00
// Fill the vector v with integers 1 to 10.
i = v.begin();
while (i != v.end())
{
*i = j;
j++;
i++;
}
2000-11-06 13:19:55 +00:00
// Square each element of v.
for (i=v.begin(); i!=v.end(); i++) *i = (*i) * (*i);
2000-11-06 13:19:55 +00:00
// Print out the vector v.
cout << "The vector v contains: ";
for (i=v.begin(); i!=v.end(); i++) cout << *i << ' ';
cout << endl;
}
2000-11-06 13:19:55 +00:00
</code>
2000-11-06 13:19:55 +00:00
Note how *i can be used on the left-hand side of an assignment statement so as to update the element pointed at by i, and on the
right-hand side to access the current value.
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
-->
<sect2> Comparing Vectors
<p>
You can compare two vectors using == and <. == will return true only if both vectors have the same number of elements and all
elements are equal. The < functions performs a lexicographic comparison of the two vectors. This works by comparing the vectors
element by element. Suppose we are comparing v1 and v2 (that is
v1 &lt v2?). Set i=0. If v1[i] &lt v2[i] then return true, if v1[i] &gt v2[i] then
return false, otherwise increment i (that is move on to the next element). If the end of v1 is reached before v2 return true, otherwise
return false. Lexicographic order is also known as dictionary order. Some examples:
2000-11-06 13:19:55 +00:00
<code>
(1,2,3,4) < (5,6,7,8,9,10) is false.
(1,2,3) < (1,2,3,4) is true
(1,2,3,4) < (1,2,3) is false
(0,1,2,3) < (1,2,3) is true
</code>
2000-11-06 13:19:55 +00:00
The following code illustrates the third example above.
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
<code>
<vector-comp.cc>=
#include <vector.h>
#include <iostream.h>
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
void main()
2000-07-10 14:17:49 +00:00
{
2000-11-06 13:19:55 +00:00
vector<int> v1;
vector<int> v2;
for (int i=0; i<4; i++) v1.push_back(i+1);
for (int i=0; i<3; i++) v2.push_back(i+1);
cout << "v1: ";
for (int i=0; i<v1.size(); i++) cout << v1[i] << ' ';
cout << endl;
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
cout << "v2: ";
for (int i=0; i<v2.size(); i++) cout << v2[i] << ' ';
cout << endl;
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
cout << "v1 < v2 is: " << (v1<v2 ? "true" : "false") << endl;
2000-07-10 14:17:49 +00:00
}
2000-11-06 13:19:55 +00:00
</code>
The comparison operators <= and >= also work.
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
-->
<sect1> Iterators and the STL
<p>
2000-11-13 15:38:38 +00:00
See the section <ref id="stlref" name="STL References">
2000-11-06 13:19:55 +00:00
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
-->
<sect1> Lists
<p>
2000-11-13 15:38:38 +00:00
See the section <ref id="stlref" name="STL References">
2000-11-06 13:19:55 +00:00
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
-->
<sect1> Sets
<p>
2001-01-12 14:53:07 +00:00
The set container type allows an user to store and retrieve elements directly rather than through an index into the container. The set container acts as a mathematical set in that it holds
only distinct elements. However unlike a mathematical set, elements in a set container are held in (an user-supplied) order. In practise this is only a minor restriction on treating a set
2000-11-06 13:19:55 +00:00
container as an implementation of the mathematical set abstract data type, and it allows for a much more efficent implementation than an unordered approach.
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
-->
<sect2> Constructing Sets
<p>
Two template arguments are required to construct a set container -- the type of the objects the set is to contain and a function object that can compare two elements of the given type,
that is:
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
<code>
set<T, Compare> s;
</code>
2000-07-10 14:17:49 +00:00
2000-11-06 13:19:55 +00:00
(The declaration <it>set &lt T &gt s</it> should also be possible -- it would
use a default template argument less &lt T &gt as the second argument, but
many C++ compilers (including g++) cannot as
yet cope with default template arguments.)
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
For simple types <bf>T</bf> we can use the function object <it>less &lt T &gt </it> (
without having to worry about what a ``function object'' is), for example all the following are legal set declarations.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
set<int, less<int> > s1;
set<double, less<double> > s2;
set<char, less<char> > s3;
set<string, less<string> > s4;
</code>
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
(Note that the space between the two final >'s in the template is required - otherwise the compiler will interpret >> as the right shift operator.) In each of these cases the function
object makes use of the operator &lt as defined for the the underlying type (that is
<it>int, double, char</it> and <it>string</it>).
2000-08-07 15:41:05 +00:00
2000-11-06 13:19:55 +00:00
The following code declares a set of integers, then adds some integers to
the set using the <it>insert</it> method and then prints out the set
members by iterating through the set. You will
note that the set's contents are printed out in ascending order even though they were added in no particular order.
2000-08-07 15:41:05 +00:00
2000-11-06 13:19:55 +00:00
<code>
<set-construct1.cc>=
#include <iostream.h>
#include <set.h>
2000-08-07 15:41:05 +00:00
2000-11-06 13:19:55 +00:00
void main()
2000-08-07 15:41:05 +00:00
{
2000-11-06 13:19:55 +00:00
set<int, less<int> > s;
set<int, less<int> >::iterator i;
2000-08-07 15:41:05 +00:00
2000-11-06 13:19:55 +00:00
s.insert(4);
s.insert(0);
s.insert(-9);
s.insert(7);
s.insert(-2);
s.insert(4);
s.insert(2);
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
cout << The set contains the elements: ;
for (i=s.begin(); i!=s.end(); i++) cout << *i << ' ';
cout << endl;
2000-08-07 15:41:05 +00:00
}
</code>
2000-11-06 13:19:55 +00:00
Note that 4 is added twice but only turns up once on the list of elements -- which is what one expects of a set.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
2000-11-06 13:19:55 +00:00
<sect2> What are Function Objects?
<p>
2000-11-06 13:19:55 +00:00
One of the nifty features of C++ is the ability to overload operators, so that one can have + mean whatever one likes for your newly designed class. One of the operators C++ allows
you to overload is the function call operator () and this allows you to create classes whose instances can behave like functions in many ways. These are function objects.
2000-11-06 13:19:55 +00:00
Here is a simple example.
2000-11-06 13:19:55 +00:00
<code>
<function-object.cc>=
#include <iostream.h>
2000-11-06 13:19:55 +00:00
template<class T>
class square {
public:
T operator()(T x) { return x*x; }
};
// This can be used with any T for which * is defined.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
void main()
2000-08-03 18:24:33 +00:00
{
2000-11-06 13:19:55 +00:00
// Create some function objects.
square<double> f1;
square<int> f2;
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
// Use them.
cout << 5.1^2 = << f1(5.1) << endl;
cout << 100^2 = << f2(100) << endl;
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
// The following would result in a compile time error.
// cout << 100.1^2 = << f2(100.1) << endl;
2000-08-03 18:24:33 +00:00
}
2000-11-06 13:19:55 +00:00
</code>
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
Function objects are used in a number of places in the STL. In particular they are used when declaring sets and maps.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
The function object required for these purposes, let's suppose it is
called <it>comp</it>, must satisfy the following requirements.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<enum>
<item> If comp(x,y) and comp(y,z) are true for objects x, y and z then comp(x,z) is also true.
<item> comp(x,x) is false for every object x.
</enum>
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
If for any particular objects x and y, both comp(x,y) and comp(y,x) are false then x and y are deemed to be equal.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
This, in fact, is just the behaviour of the <it>strictly-less-than</it>
relation (ie &lt ) on numbers. The function object less &lt T &gt used above is
defined in terms of a &lt operator for the type T. It's
definition can be thought of as follows.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
template<class T>
struct less {
bool operator()(T x, T y) { return x<y; }
2000-08-03 18:24:33 +00:00
}
2000-11-06 13:19:55 +00:00
</code>
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
(The actual definition uses references, has appropriate const annotations and inherits from a template class binary_function.)
2000-11-06 13:19:55 +00:00
This means that if the type T has operator &lt defined for it then you can use
less &lt T &gt as the comparator when declaring sets of T. You might still want to use a special purpose
comparator if the supplied &lt operator is not appropriate for
your purposes. Here is another example. This defines a simple
class with a definition of operator &lt and a function object
that performs a different comparison. Note that the overloaded &lt
and () operators should be given const annotations so that the functions
work correctly with the STL.
2000-08-03 18:24:33 +00:00
2000-11-06 13:19:55 +00:00
<code>
<set-construct2.cc>=
#include <iostream.h>
#include <set.h>
// This class has two data members. The overloaded operator< compares
// such classes on the basis of the member f1.
class myClass {
private:
int f1;
char f2;
public:
myClass(int a, char b) : f1(a), f2(b) {}
int field1() const { return f1; }
char field2() const { return f2; }
bool operator<(myClass y) const
{ return (f1<y.field1()); }
};
2000-11-06 13:19:55 +00:00
// This function object compares objects of type myClass on the basis
// of the data member f2.
class comp_myClass {
public:
bool operator()(myClass c1, myClass c2) const
{ return (c1.field2() < c2.field2()); }
};
2000-11-06 13:19:55 +00:00
void main()
{
2000-11-06 13:19:55 +00:00
set<myClass, less<myClass> > s1;
set<myClass, less<myClass> >::iterator i;
set<myClass, comp_myClass> s2;
set<myClass, comp_myClass>::iterator j;
2000-11-06 13:19:55 +00:00
s1.insert(myClass(1,'a'));
s2.insert(myClass(1,'a'));
s1.insert(myClass(1,'b'));
s2.insert(myClass(1,'b'));
s1.insert(myClass(2,'a'));
s2.insert(myClass(2,'a'));
2000-11-06 13:19:55 +00:00
cout << Set s1 contains: ;
for (i=s1.begin(); i!=s1.end(); i++)
{ cout << ( << (*i).field1() << ,
<< (*i).field2() << ) << ' ';
}
cout << endl;
cout << Set s2 contains: ;
for (j=s2.begin(); j!=s2.end(); j++)
{ cout << ( << (*j).field1() << ,
<< (*j).field2() << ) << ' ';
}
cout << endl;
}
2000-11-06 13:19:55 +00:00
</code>
2000-11-06 13:19:55 +00:00
The set s1 contains (1,a) and (2,a) as comparison is on the data member f1, so that (1,a) and (1,b) are deemed the same element. The set s2 contains (1,a) and (1,b) as
comparison is on the data member f2, so that (1,a) and (2,a) are deemed the same element.
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
-->
<sect2> A Printing Utility
<p>
The way we have printed out the sets in the previous examples is a little awkward so the following header file containing a simple overloaded version
of <it>operator<< </it> has been written.
It works fine for small sets with simple element types.
2000-11-06 13:19:55 +00:00
<code>
<printset.h>=
#ifndef _PRINTSET_H
#define _PRINTSET_H
#include <iostream.h>
#include <set.h>
2000-11-06 13:19:55 +00:00
template<class T, class Comp>
ostream& operator<<(ostream& os, const set<T,Comp>& s)
{
2000-11-06 13:19:55 +00:00
set<T,Comp>::iterator iter = s.begin();
int sz = s.size();
int cnt = 0;
2000-11-06 13:19:55 +00:00
os << {;
while (cnt < sz-1)
{
os << *iter << ,;
iter++;
cnt++;
}
if (sz != 0) os << *iter;
os << };
2000-11-06 13:19:55 +00:00
return os;
}
2000-11-06 13:19:55 +00:00
#endif
</code>
2000-11-06 13:19:55 +00:00
The use here of << as an output routine for a set assumes that << has been defined for the set elements, and uses this to print a comma delimited list of the set elements wrapped in
curly braces. It will be used without comment in the following examples.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
2000-11-06 13:19:55 +00:00
<sect2> How Many Elements?
<p>
2000-11-06 13:19:55 +00:00
You can determine if a set is empty or not by using the empty() method. You can find out how many elements there are in a set by using the size() method. These methods take no
arguments, empty() returns true or false and size() returns an integer.
2000-10-30 15:40:21 +00:00
2000-11-06 13:19:55 +00:00
<code>
<set-size.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h
2000-11-06 13:19:55 +00:00
void main()
{
set<int, less<int> > s;
2000-11-06 13:19:55 +00:00
cout << The set s is
<< (s.empty() ? empty. : non-empty.) << endl;
cout << It has << s.size() << elements. << endl;
2000-11-06 13:19:55 +00:00
cout << Now adding some elements... << endl;
2000-11-06 13:19:55 +00:00
s.insert(1);
s.insert(6);
s.insert(7);
s.insert(-7);
s.insert(5);
s.insert(2);
s.insert(1);
s.insert(6);
2000-11-06 13:19:55 +00:00
cout << The set s is now
<< (s.empty() ? empty. : non-empty.) << endl;
cout << It has << s.size() << elements. << endl;
cout << s = << s << endl;
}
</code>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
-->
<sect2> Checking the Equality of Sets.
<p>
Two sets may be checked for equality by using ==. This equality test works by testing in order the corresponding elements of each set for equality using T::operator==.
2000-11-06 13:19:55 +00:00
<code>
<set-equality.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h
void main()
{
set<int, less<int> > s1, s2 ,s3;
for (int i=0; i<10; i++)
{
s1.insert(i);
s2.insert(2*i);
s3.insert(i);
}
cout << s1 = << s1 << endl;
cout << s2 = << s2 << endl;
cout << s3 = << s3 << endl;
cout << s1==s2 is: << (s1==s2 ? true. : false.) << endl;
cout << s1==s3 is: << (s1==s3 ? true. : false.) << endl;
}
</code>
2000-11-06 13:19:55 +00:00
It is also possible to compare two sets using <. The comparison s1 < s2 is true if the set s1 is lexicographically less than the set s2, otherwise it is false.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
2000-11-06 13:19:55 +00:00
<sect2> Adding and Deleting Elements
<p>
2000-11-06 13:19:55 +00:00
The way to add elements to a set is to use the insert method (as we have done above). The way to delete elements from a set is to use the erase method.
For a set holding elements of type T these methods come in following forms:
<itemize>
<item> <bf>pair &lt iterator, bool> insert(T& x)</bf>. This is the standard insert function. The return value may be ignored or used to test if the insertion succeeded (that is the element
was not already in the set). If the insertion succeeded the boolean component will be true and the iterator will point at the just inserted element. If the element is already
present the boolean component will be false and the iterator will point at the element x already present.
<p>
<item> <bf>iterator insert(iterator position, T& x)</bf>. This version of the insert function takes, in addition to the element to insert, an iterator stating where the insert function
should begin to search. The returned iterator points at the newly inserted element, (or the already present element).
<p>
<item> <bf>int erase(T& x)</bf>. This version of the erase method takes an element to delete and returns 1 if the element was present (and removes it) or 0 if the element was not present.
<p>
<item> <bf>void erase(iterator position)</bf>. This version takes an iterator pointing at some element in the set and removes that element.
<p>
<item> <bf>void erase(iterator first, iterator last)</bf>. This verion takes two
iterators pointing into the set and removes all the elements in the range &lsqb first,last &rsqb .
</itemize>
2000-07-05 17:23:44 +00:00
2000-11-06 13:19:55 +00:00
The following example illustrates these various forms.
2000-11-06 13:19:55 +00:00
<code>
<set-add-delete.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h
void main()
{
set<int, less<int> > s1;
// Insert elements in the standard fashion.
s1.insert(1);
s1.insert(2);
s1.insert(-2);
// Insert elements at particular positions.
s1.insert(s1.end(), 3);
s1.insert(s1.begin(), -3);
s1.insert((s1.begin()++)++, 0);
cout << s1 = << s1 << endl;
// Check to see if an insertion has been successful.
pair<set<int, less<int> >::iterator,bool> x = s1.insert(4);
cout << Insertion of 4 << (x.second ? worked. : failed.)
<< endl;
x = s1.insert(0);
cout << Insertion of 0 << (x.second ? worked. : failed.)
<< endl;
// The iterator returned by insert can be used as the position
// component of the second form of insert.
cout << Inserting 10, 8 and 7. << endl;
s1.insert(10);
x=s1.insert(7);
s1.insert(x.first, 8);
cout << s1 = << s1 << endl;
// Attempt to remove some elements.
cout << Removal of 0 << (s1.erase(0) ? worked. : failed.)
<< endl;
cout << Removal of 5 << (s1.erase(5) ? worked. : failed.)
<< endl;
// Locate an element, then remove it. (See below for find.)
cout << Searching for 7. << endl;
set<int,less<int> >::iterator e = s1.find(7);
cout << Removing 7. << endl;
s1.erase(e);
cout << s1 = << s1 << endl;
// Finally erase everything from the set.
cout << Removing all elements from s1. << endl;
s1.erase(s1.begin(), s1.end());
cout << s1 = << s1 << endl;
cout << s1 is now << (s1.empty() ? empty. : non-empty.)
<< endl;
}
</code>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
-->
<sect2> Finding Elements
<p>
2000-11-06 13:19:55 +00:00
We mention two member functions that can be used to test if an element is present in a set or not.
2000-11-06 13:19:55 +00:00
<itemize>
<item> <bf>iterator find(T& x)</bf>. This searches for the element x in the set. If x is found it returns an iterator pointing at x otherwise it returns end().
<item> <bf>int count(T& x)</bf>. This returns 1 if it finds x in the set and 0 otherwise. (The count function for multisets returns the number of copies of the element in the set which may be
more than 1. Hence, I guess, the name of the function.)
</itemize>
2000-11-06 13:19:55 +00:00
The use of find has been illustrated above. We could use count to write a simple template based set membership function. (This should also provide a version that takes a reference
to the argument x.)
2000-11-06 13:19:55 +00:00
<code>
<setmember.h>=
#ifndef _SETMEMBER_H
#define _SETMEMBER_H
#include <set.h>
2000-11-06 13:19:55 +00:00
template<class T, class Comp>
bool member(T x, set<T,Comp>& s)
{
return (s.count(x)==1 ? true : false);
}
#endif
2000-11-06 13:19:55 +00:00
Which might be used as follows.
2000-11-06 13:19:55 +00:00
<set-membership.cc>=
#include <iostream.h>
#include <set.h>
#include printset.h
#include setmember.h
2000-11-06 13:19:55 +00:00
void main()
{
set<int, less<int> > s;
for (int i= 0; i<10; i++) s.insert(i);
cout << s = << s << endl;
cout << 1 is << (member(1,s) ? : not) << a member of s
<< endl;
cout << 10 is << (member(10,s) ? : not) << a member of s
<< endl;
}
</code>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
-->
<sect2> Set Theoretic Operations
<p>
2000-11-06 13:19:55 +00:00
The STL supplies as generic algorithms the set operations includes, union, intersection, difference and symmetric diffference. To gain access to these functions you need to include
algo.h. (In what follows iter stands for an appropriate iterator).
2000-11-06 13:19:55 +00:00
<itemize>
<item> bool includes(iter f1,iter l1,iter f2,iter l2).
<p>
This checks to see if the set represented by the range [f2,l2] is included in the set [f1,l1]. It returns true if it is and false otherwise. So to check to see if one set is
included in another you would use
<p>
2000-11-06 13:19:55 +00:00
includes(s1.begin(), s1.end(), s2.begin(), s2.end())
<p>
The includes function checks the truth of 3#3 ( that is of 4#4). This function assumes that the sets are ordered using the comparison operator <. If some other comparison
operator has been used this needs to be passed to includes as an extra (function object) argument after the other arguments.
<p>
<item> iter set_union(iter f1,iter l1,iter f2,iter l2,iter result).
<p>
This forms the union of the sets represented by the ranges [f1,l1] and [f2,l2]. The argument result is an output iterator that points at the start of the set that is going to
hold the union. The return value of the function is an output iterator that points at the end of the new set.
</itemize>
The fact that the result argument is an output iterator means that you cannot use set_union in the following, natural, fashion:
<code>
set<int, less<int> > s1, s2, s3;
// Add some elements to s1 and s2 ...
// Then form their union. (This does not work!)
set_union(s1.begin(), s1.end(),
s2.begin(), s2.end(),
s3.begin());
</code>
The reason is that begin() (also end()) when used with sets (or maps) returns a (constant) input iterator. This type of iterator allows you to access elements of the set for
reading but not writing. (And this is a Good Thing since if you could assign to a dereferenced iterator (as in (*i)= ...) then you could destroy the underlying order of the
set.)
The solution is to use an insert iterator based on the set type. This, basically, converts an assignment (*i)=value (which is illegal) into a (legal) insertion
s.insert(i,value) (where s is the set object that the iterator i is pointing into). It is used as follows:
<code>
2000-11-06 13:19:55 +00:00
// Typedef for convenience.
typedef set<int, less<int> > intSet;
intSet s1, s2, s3;
// Add some elements to s1 and s2 ...
// Then form their union.
set_union(s1.begin(), s1.end(),
s2.begin(), s2.end(),
insert_iterator<intSet>(s3,s3.begin()) );
</code>
Here is an example illustrating all these operations.
<code>
<set-theory.cc>=
#include <iostream.h>
#include <set.h>
#include <algo.h>
#include <iterator.h>
#include printset.h
void main()
{
typedef set<int, less<int> > intSet;
intSet s1, s2, s3, s4;
for (int i=0; i<10; i++)
{ s1.insert(i);
s2.insert(i+4);
}
for (int i=0; i<5; i++) s3.insert(i);
cout << s1 = << s1 << endl;
cout << s2 = << s2 << endl;
cout << s3 = << s3 << endl;
// Is s1 a subset of s2?
bool test = includes(s2.begin(),s2.end(),s1.begin(),s1.end());
cout << s1 subset of s2 is << (test ? true. : false.) << endl;
// Is s3 a subset of s1?
test = includes(s1.begin(),s1.end(),s3.begin(),s3.end());
cout << s3 subset of s1 is << (test ? true. : false.) << endl;
// Form the union of s1 and s2.
set_union(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s1 union s2 = << s4 << endl;
// Erase s4 and form intersection of s1 and s2. (If we don't erase
// s4 then we will get the previous contents of s4 as well).
s4.erase(s4.begin(),s4.end());
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s1 intersection s2 = << s4 << endl;
// Now set difference.
s4.erase(s4.begin(),s4.end());
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s1 minus s2 = << s4 << endl;
// Set difference is not symmetric.
s4.erase(s4.begin(),s4.end());
set_difference(s2.begin(), s2.end(), s1.begin(), s1.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s2 minus s1 = << s4 << endl;
// Finally symmetric difference.
s4.erase(s4.begin(),s4.end());
set_symmetric_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s1 symmetric_difference s2 = << s4 << endl;
// Which is symmetric!
s4.erase(s4.begin(),s4.end());
set_symmetric_difference(s2.begin(), s2.end(), s1.begin(), s1.end(),
insert_iterator<intSet>(s4,s4.begin()) );
cout << s2 symmetric_difference s1 = << s4 << endl;
}
</code>
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
-->
<sect1> Maps
<p>
2000-11-13 15:38:38 +00:00
See the section <ref id="stlref" name="STL References">
2000-11-06 13:19:55 +00:00
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
2000-11-06 13:19:55 +00:00
<sect1> STL Algorithms
<p>
2000-11-13 15:38:38 +00:00
See the section <ref id="stlref" name="STL References">
<!--
*******************************************
************ End of Section ***************
*******************************************
2001-02-06 14:26:14 +00:00
<chapt> Threads in C++
-->
<sect> Threads in C++
<p>
<itemize>
<item> IBM pthread User Guide, Thread concepts, API reference
<url url="http://www.as400.ibm.com/developer/threads/uguide/document.htm">
and mirror site is at
<url name="IBM main site" url="http://java.icmc.sc.usp.br/library/books/ibm_pthreads/document.htm">
<p>
<item> QpThread Library for C++ provides object oriented framework in C++
for threads and Unix signals on top of system level threads (currently POSIX Threads)
<url url="http://lin.fsid.cvut.cz/~kra/index.html">
<p>
<item> ThreadJack supports Java-like multi-thread programming
model with platform independent C++ class library
<url url="http://www.esm.co.jp/divisions/open-sys/ThreadJack/index-e.html">
and here is the
<url name="download-site" url="http://www.esm.co.jp/divisions/open-sys/ThreadJack/source-dl-e.html">
<p>
<item> APE is the "APE Portable Environment" and class libraries for
writing portable threaded servers in C++, under UNIX (pthread) and Win32 API's.
APE provides portable class abstraction for threads, sockets, file handling, and
synchronization objects. The goal of APE is to make writing threaded
servers in C++ both practical and convient, even for small
and simple projects, and hence simplicity and low runtime overhead
are design goals <url url="http://www.voxilla.org/projects/projape.html">
<p>
<item> Portabale Thread Lib <url url="http://www.media.osaka-cu.ac.jp/~k-abe/PTL">
<p>
<item> Thread-Recyling in C++ <url url="http://www.sigs.de/html/kuhlmann.html">
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2001-03-12 14:15:47 +00:00
-->
<sect1> Threads Tutorial
<p>
<itemize>
<item> You can download all the tutorials in one file from
<url name="aldev-site" url="http://www.aldev.8m.com/cppsrc.html">
<p>
<item> Threads tutorial is at <url url="http://www.math.arizona.edu/swig/pthreads/threads.html">
<p>
<item> HERT tutorial at <url url="http://www.hert.org/docs/tutorials">, go here to
search for "Threads".
<p>
<item> Intro to threads at <url name="linuxjournal" url="http://www2.linuxjournal.com/lj-issues/issue61/3138.html">
<p>
<item>North Arizona Univ <url name="NAU" url="http://www.cse.nau.edu/~mc8/Thread/Contents.html">
<p>
<item> Posix threads <url name="Acctcom multi-thread" url="http://users.actcom.co.il/~choo/lupg/tutorials/multi-thread/multi-thread.html">
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
2001-02-06 14:26:14 +00:00
-->
<sect1> Designing a Thread Class in C++
<p>
This section is written by
<htmlurl url="mailto:ryte@geocities.com"
name="Ryan Teixeira">
and the document is located
<url name="here" url="http://www.geocities.com/SiliconValley/Heights/6038/dthreads.html">
.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect2> Introduction
<p>
Multi threaded programming is becomming ever more popular. This section
presents a design for a C++ class that will encapsulate the threading
mechanism. Certain aspects of thread programming, like mutexes and semaphores
are not discussed here. Also, operating system calls to manipulate threads are
shown in a generic form.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect2> Brief Introduction To Threads
<p>
To understand threads one must think of several
programs running at once. Imagine further
that all these programs have access to the same set of
global variables and function calls.
Each of these programs would represent a thread of
execution and is thus called a thread.
The important differentiation is that each thread does not have to wait
for any other thread to proceed. All the threads proceed
simultaneously. To use a metaphor, they are like runners
in a race, no runner waits for another runner. They
all proceed at their own rate.
Why use threads you might ask. Well threads can often
improve the performance of an application and they do not incur
significant overhead to implement. They effectively give
good bang for a buck. Imagine an image server program
that must service requests for images.
The program gets a request for an image from another program. It must
then retieve the image from a database and send it to the program that
requested it. If the server were implemented in a single threaded
approach, only one program could request at a time. When it was busy
retrieving an image and sending it to a requestor, it could not
service other requests. Of course one could still implement such a system without
using threads. It would be a challenge though. Using threads, one can very
naturally design a system to handle multiple requests. A simple approach
would be to create a thread for each request received. The main
thread would create this thread upon receipt of a request. The thread
would then be responsible for the conversation with the client
program from that point on. After retrieving the image, the thread would
terminate itself. This would provide a smooth system
that would continue to service requests even though it
was busy serviceing other requests at the same time.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect2> Basic Approach
<p>
The create a thread, you must specify a function that will become the entry
point for the thread. At the operating system level, this is a
normal function. We have to do a few tricks to wrap a C++ class around it
because the entry function cannot be a normal member function
of a class. However, it can be a static member function of a class. This is
what we will use as the entry point. There is a gotcha here though.
Static member functions do not have access to the this pointer of
a C++ object. They can only access static data. Fortunately,
there is way to do it. Thread entry point functions take a void *
as a parameter so that the caller can typecast any data and pass in to
the thread. We will use this to pass this to the static function. The static
function will then typecast the void * and use it to call a non
static member function.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect2> The Implementation
<p>
It should be mentioned that we are going to discuss a thread class with
limited functionality. It is possible to do more with threads
than this class will allow.
<code>
class Thread
{
public:
Thread();
int Start(void * arg);
protected:
int Run(void * arg);
static void * EntryPoint(void*);
virtual void Setup();
virtual void Execute(void*);
void * Arg() const {return Arg_;}
2001-02-24 15:51:34 +00:00
void Arg(void* a){Arg_ = a;}
2001-02-06 14:26:14 +00:00
private:
THREADID ThreadId_;
void * Arg_;
};
Thread::Thread() {}
int Thread::Start(void * arg)
{
Arg(arg); // store user data
int code = thread_create(Thread::EntryPoint, this, & ThreadId_);
return code;
}
int Thread::Run(void * arg)
{
Setup();
Execute( arg );
}
/*static */
void * Thread::EntryPoint(void * pthis)
{
Thread * pt = (Thread*)pthis;
pthis->Run( Arg() );
}
virtual void Thread::Setup()
{
// Do any setup here
}
virtual void Thread::Execute(void* arg)
{
// Your code goes here
}
</code>
It is important to understand that we are wrapping a C++ object
around a thread. Each object will provide an interface to a single thread. The
thread and the object are not the same.
The object can exist without a thread. In this implementation, the
thread does not actually exist until the Start function is called.
Notice that we store the user argument in the class.
This is necessary because we need a place to store it temporarily until the thread is
started. The operating system thread call allows us to pass an argument but we have used it to
pass the this pointer. So we store the real user argument in the class itself and when the
execute function is called it can get access to the argument.
<bf>Thread(); </bf>
This is the constructor.
<bf>int Start(void * arg); </bf>
This function provides the means to create the thread
and start it going. The argument arg provides a way for user data to be passed into the
thread. Start() creates the thread by calling the operating system thread creation function.
<bf>int Run(void * arg); </bf>
This is a protected function that should never be
tampered with.
<bf>static void * EntryPoint(void * pthis); </bf>
This function serves as the entry point to the thread.
It simply casts pthis to Thread * and
<bf>virtual void Setup(); </bf>
This function is called after the thread has been
created but before Execute() is called. If you override this function, remember to call the
parent class Execute().
<bf>virtual void Execute(void *); </bf>
You must override this function to provide your own
functionality.
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect2> Using The Thread Class
<p>
To use the thread class, you derive a new class. you
override the Execute() function where you provide your own functionality. You may override
the Setup() function to do any start up
duties before Execute is called. If you override
Setup(), remember to call the parent class Setup().
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
<sect2> Conclusion
<p>
This section presented an implementation of a thread class written in C++.
Of course it is a simple approach but it provides a sound foundation
upon which to build a more robust design.
If you have comments or suggestions, email to
<htmlurl url="mailto:ryte@geocities.com"
name="Ryan Teixeira">
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-13 15:38:38 +00:00
<chapt change> C++ Utilities
-->
<sect> C++ Utilities
<p>
Visit the following sites for C++ Utilities
<itemize>
<item> C++ Binary File I/O
<url url="http://www.angelfire.com/nv/aldev/cpphowto/cpp_BinaryFileIO.html">
and at <url url="http://aldev.50megs.com/cpphowto/cpp_BinaryFileIO.html" name="mirror site">
<p>
<item> Portability Guide
<url url="http://www.angelfire.com/nv/aldev/cpphowto/cpp_PortabilityGuide.html">
and at <url url="http://aldev.50megs.com/cpphowto/cpp_PortabilityGuide.html" name="mirror site">
<p>
<item> Snippets collections of C++ routines
<url url="http://www.angelfire.com/nv/aldev/cpphowto/cpp_Snippets.html">
and at <url url="http://aldev.50megs.com/cpphowto/cpp_Snippets.html" name="mirror site">
and at <url url="http://www.strangecreations.com/library/snippets" name="snippets site">
2001-02-06 14:26:14 +00:00
<p>
<item> escape ISB for C++ - Provides information on how to
develop and program distributed, object-based applications in C++ for
Windows and Unix using the Netscape Internet Service Broker
<url url="http://docs.iplanet.com/docs/manuals/enterprise/cpluspg/contents.htm">
<p>
<item> Common c++ <url url="http://www.voxilla.org/projects/projape.html">
<p>
<item> Large List of free C++ libs
<url url="http://www.thefreecountry.com/developercity/freelib.html">
<p>
<item> C++ Tools <url url="http://development.freeservers.com">
<p>
<item> C++ Tools CUJ <url url="http://www.cuj.com/code">
<p>
<item> C++libs Univ of vaasa <url url="http://garbo.uwasa.fi/pc/c-lang.html">
2000-11-13 15:38:38 +00:00
</itemize>
2000-11-06 13:19:55 +00:00
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
<chapt change> Other Formats of this Document
-->
<sect> Other Formats of this Document
<p>
2000-12-23 00:32:23 +00:00
This document is published in 12 different formats namely - DVI, Postscript,
2000-11-06 13:19:55 +00:00
Latex, Adobe Acrobat PDF,
2000-12-23 00:32:23 +00:00
LyX, GNU-info, HTML, RTF(Rich Text Format), Plain-text, Unix man pages,
single HTML file and SGML.
2000-11-06 13:19:55 +00:00
<itemize>
<item>
You can get this HOWTO document as a single file tar ball in HTML, DVI,
Postscript or SGML formats from -
<url url="ftp://sunsite.unc.edu/pub/Linux/docs/HOWTO/other-formats/">
2001-02-01 14:40:35 +00:00
and <url url="http://www.linuxdoc.org/docs.html#howto">
2000-11-06 13:19:55 +00:00
<item>Plain text format is in: <url url="ftp://sunsite.unc.edu/pub/Linux/docs/HOWTO">
2001-02-01 14:40:35 +00:00
and <url url="http://www.linuxdoc.org/docs.html#howto">
<item>Single HTML file format is in:
<url url="http://www.linuxdoc.org/docs.html#howto">
2000-11-06 13:19:55 +00:00
<item>Translations to other languages like French, German, Spanish,
Chinese, Japanese are in
<url url="ftp://sunsite.unc.edu/pub/Linux/docs/HOWTO">
2001-02-01 14:40:35 +00:00
and <url url="http://www.linuxdoc.org/docs.html#howto">
2000-11-06 13:19:55 +00:00
Any help from you to translate to other languages is welcome.
</itemize>
The document is written using a tool called "SGML-Tools" which can be got from -
<url url="http://www.sgmltools.org">
Compiling the source you will get the following commands like
<itemize>
<item>sgml2html C++Programming-HOWTO.sgml (to generate html file)
<item>sgml2rtf C++Programming-HOWTO.sgml (to generate RTF file)
<item>sgml2latex C++Programming-HOWTO.sgml (to generate latex file)
</itemize>
2000-11-06 13:19:55 +00:00
LaTeX documents may be converted into PDF files simply by
producing a Postscript output using <bf>sgml2latex</bf> ( and dvips) and running the
output through the Acrobat <bf>distill</bf> (<url url="http://www.adobe.com">) command as follows:
<code>
bash$ man sgml2latex
bash$ sgml2latex filename.sgml
bash$ man dvips
bash$ dvips -o filename.ps filename.dvi
bash$ distill filename.ps
bash$ man ghostscript
bash$ man ps2pdf
bash$ ps2pdf input.ps output.pdf
bash$ acroread output.pdf &
</code>
Or you can use Ghostscript command <bf>ps2pdf</bf>.
ps2pdf is a work-alike for nearly all the functionality of
Adobe's Acrobat Distiller product: it
converts PostScript files to Portable Document Format (PDF) files.
<bf>ps2pdf</bf> is implemented as a very small command script (batch file) that invokes Ghostscript, selecting a special "output device"
called <bf>pdfwrite</bf>. In order to use ps2pdf, the pdfwrite device must be included in the makefile when Ghostscript was compiled;
see the documentation on building Ghostscript for details.
2000-11-06 13:19:55 +00:00
This howto document is located at -
<itemize>
<item> <url url="http://sunsite.unc.edu/LDP/HOWTO/C++Programming-HOWTO.html">
</itemize>
2000-11-06 13:19:55 +00:00
Also you can find this document at the following mirrors sites -
<itemize>
<item> <url url="http://www.caldera.com/LDP/HOWTO/C++Programming-HOWTO.html">
<item> <url url="http://www.WGS.com/LDP/HOWTO/C++Programming-HOWTO.html">
<item> <url url="http://www.cc.gatech.edu/linux/LDP/HOWTO/C++Programming-HOWTO.html">
<item> <url url="http://www.redhat.com/linux-info/ldp/HOWTO/C++Programming-HOWTO.html">
2000-11-06 13:19:55 +00:00
<item> Other mirror sites near you (network-address-wise) can be found at
<url url="http://sunsite.unc.edu/LDP/hmirrors.html">
select a site and go to directory /LDP/HOWTO/C++Programming-HOWTO.html
</itemize>
2000-06-05 15:07:57 +00:00
2000-11-06 13:19:55 +00:00
In order to view the document in dvi format, use the xdvi program. The xdvi
program is located in tetex-xdvi*.rpm package in Redhat Linux which can be
located through ControlPanel | Applications | Publishing | TeX menu buttons.
To read dvi document give the command -
<tscreen><verb>
xdvi -geometry 80x90 howto.dvi
man xdvi
</verb></tscreen>
And resize the window with mouse.
To navigate use Arrow keys, Page Up, Page Down keys, also
you can use 'f', 'd', 'u', 'c', 'l', 'r', 'p', 'n' letter
keys to move up, down, center, next page, previous page etc.
To turn off expert menu press 'x'.
2000-11-06 13:19:55 +00:00
You can read postscript file using the program 'gv' (ghostview) or
'ghostscript'.
The ghostscript program is in ghostscript*.rpm package and gv
program is in gv*.rpm package in Redhat Linux
which can be located through ControlPanel | Applications | Graphics menu
buttons. The gv program is much more user friendly than ghostscript.
Also ghostscript and gv are available on other platforms like OS/2,
Windows 95 and NT, you view this document even on those platforms.
<itemize>
<item>Get ghostscript for Windows 95, OS/2, and for all OSes from <url url="http://www.cs.wisc.edu/~ghost">
</itemize>
2000-11-06 13:19:55 +00:00
To read postscript document give the command -
<tscreen><verb>
gv howto.ps
ghostscript howto.ps
</verb></tscreen>
2000-11-06 13:19:55 +00:00
You can read HTML format document using Netscape Navigator, Microsoft Internet
explorer, Redhat Baron Web browser or any of the 10 other web browsers.
2000-11-06 13:19:55 +00:00
You can read the latex, LyX output using LyX a X-Windows front end to latex.
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-06 13:19:55 +00:00
<chapt> Copyright
-->
<sect> Copyright
<p>
Copyright policy is GNU/GPL as per LDP (Linux Documentation project).
LDP is a GNU/GPL project.
Additional requests are that you retain the author's name, email address
and this copyright notice on all the copies. If you make any changes
or additions to this document then you please
intimate all the authors of this document.
Brand names mentioned in this document are property of their respective
owners.
<!--
*******************************************
************ End of Section ***************
*******************************************
2000-11-13 15:38:38 +00:00
<chapt> Appendix A String Program Files <label id="Appendix A">
2000-11-06 13:19:55 +00:00
-->
2000-11-13 15:38:38 +00:00
<sect> Appendix A String Program Files <label id="Appendix A">
2000-11-06 13:19:55 +00:00
<p>
2000-12-18 15:01:28 +00:00
You can <bf>download all programs as a single tar.gz</bf> file from
<ref id="Download String">
and give the following command to unpack
<code>
2000-12-23 00:32:23 +00:00
bash$ man tar
2000-12-18 15:01:28 +00:00
bash$ tar ztvf C++Programming-HOWTO.tar.gz
This will list the table of contents
bash$ tar zxvf C++Programming-HOWTO.tar.gz
This will extract the files
</code>
<itemize>
<item> Read the header file first and then see the example cpp program
2000-11-06 13:19:55 +00:00
<itemize>
<item> String.h
<url url="http://www.angelfire.com/nv/aldev/cpphowto/String.h">
2000-12-18 15:01:28 +00:00
<item> string_multi.h
<url url="http://www.angelfire.com/nv/aldev/cpphowto/string_multi.h">
<item> example_String.cpp
<url url="http://www.angelfire.com/nv/aldev/cpphowto/example_String.cpp">
</itemize>
<p>
<item> File manipulation class, only length() function is implemented..
<itemize>
2000-11-13 15:38:38 +00:00
<item> File.h
<url url="http://www.angelfire.com/nv/aldev/cpphowto/File.h">
<item> File.cpp
<url url="http://www.angelfire.com/nv/aldev/cpphowto/File.cpp">
2000-12-18 15:01:28 +00:00
</itemize>
<p>
<item> The zap() implemented here ..
<itemize>
2000-11-06 13:19:55 +00:00
<item> my_malloc.h
<url url="http://www.angelfire.com/nv/aldev/cpphowto/my_malloc.h">
2000-12-18 15:01:28 +00:00
<item> my_malloc.cpp
<url url="http://www.angelfire.com/nv/aldev/cpphowto/my_malloc.cpp">
</itemize>
<p>
<item> Implementation of string class...
<itemize>
<item> String.cpp
<url url="http://www.angelfire.com/nv/aldev/cpphowto/String.cpp">
<item> StringTokenizer.cpp
<url url="http://www.angelfire.com/nv/aldev/cpphowto/StringTokenizer.cpp">
</itemize>
<p>
<item> Debug facilities ..
<itemize>
2000-11-06 13:19:55 +00:00
<item> debug.h
<url url="http://www.angelfire.com/nv/aldev/cpphowto/debug.h">
<item> debug.cpp
<url url="http://www.angelfire.com/nv/aldev/cpphowto/debug.cpp">
<item> Makefile
<url url="http://www.angelfire.com/nv/aldev/cpphowto/Makefile">
2000-12-18 15:01:28 +00:00
</itemize>
2001-03-17 15:32:41 +00:00
<p>
<item> Sample java file for testing the functionalities of String class ..
<itemize>
<item> string.java
<url url="http://www.angelfire.com/nv/aldev/cpphowto/string.java">
</itemize>
2000-11-06 13:19:55 +00:00
</itemize>
<!--
*******************************************
************ End of Section ***************
*******************************************
-->
</article>