Penguin
Note: You are viewing an old revision of this page. View the current version.

C++ Programming HOW-TO

Al Dev (Alavoor Vasudevan)

alavoor[AT?yahoo.comv42.3, 23 May 2002

Want to know how to ConvertingAnIntegerToaStringInCpp or C++ or related languages?


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 that is - Linux, MS DOS, BeOS, Apple Macintosh OS, Microsoft Windows 95/98/NT/2000, 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 supplies C++ compilers (it means almost all the operating systems on this planet).


1. Introduction

  • 1.1 Program in C++ ? C++ vs. Java/PHP
  • 1.2 Which one Ada95, C, C++, Java or PHP?
  • 1.3 Problems facing the current C++ compilers

2. Recommended C++ Compilers

  • 2.1 Compilers for MS Windows 2000/NT/95/98/ME/XP
  • 2.2 Compilers for UNIX systems and clones

3. String Class Varieties

  • 3.1 Multiple Inheritance - Sample Custom String class

4. Download String

  • 4.1 How Can I trust Al Dev's String Class?

5. Usage of String class

  • 5.1 Operators
  • 5.2 Functions
  • 5.3 Renaming the String class

6. String.h file

  • 6.1 !StringBuffer?.h
  • 6.2 !StringTokenizer?.h

7. The Standard C++ Library string class

  • 7.1 string by example
  • 7.2 Searching a string
  • 7.3 A string tokenizer

8. File Class

9. Memory Allocation in C++

  • 9.1 C++ Zap (Delete) function
  • 9.2 Usage of my_malloc and my_free
  • 9.3 Garbage Collector for C++

10. Pointers are problems

11. Debugging

  • 11.1 Debug files

12. IDE's and editors for C++

  • 12.1 IDE's
  • 12.2 Editors
  • 12.3 Other ressources

13. C++ Online Textbooks and Docs

  • 13.1 C++ Sites
  • 13.2 C++ Tutorials
  • 13.3 Useful links
  • 13.4 C++ Quick-Reference
  • 13.5 C++ Usenet Newsgroups
  • 13.6 Java like API

14. C++ Coding Conventions

15. C++ Scripting Languages

  • 15.1 PIKE & PHP (C/C++ Scripting Languages)
  • 15.2 !SoftIntegration? Ch (C/C++ Scripting Language)
  • 15.3 PHP (C++ Scripting Language)

16. Templates

17. STL References

  • 17.1 Overview of the STL
  • 17.2 Header Files
  • 17.3 The Container Classes Interface
  • 17.4 Vectors
  • 17.5 Iterators and the STL
  • 17.6 Lists
  • 17.7 Sets
  • 17.8 Maps
  • 17.9 STL Algorithms

18. Threads in C++

  • 18.1 Threads Tutorial
  • 18.2 Designing a Thread Class in C++

19. C++ Utilities

  • 19.1 Memory Tools

20. Other Formats of this Document

  • 20.1 Acrobat PDF format
  • 20.2 Convert linuxdoc to Docbook format
  • 20.3 Convert to MS !WinHelp? format
  • 20.4 Reading various formats

21. Translations To Other Languages

22. Copyright

23. Appendix A String Program Files


1. Introduction

(The latest version of this document is at http://www.milkywaygalaxy.freeservers.com. You may want to check there for changes).

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 Java-like String class, string tokenizer, memory functions and many other functions, which can be used in general C++ applications. C++ and Java is often used concurrently in many software projects. Programmers jump back and forth between C++ and Java will find this Java-like classes very helpful. Various examples are given which demonstrate the usage of this library and the Standard C++ Library.

This document is not a textbook on C++, and there are already several excellent on-line text books on the internet. Since C++ is being used for a long time there are very large number of C++ documents/articles/tutorials on Internet. If you are new to C++ and you never programmed in C++, then it is strongly suggested that you first either read an online C++ textbook given in chapter C++ Online Textbooks or you buy a C++ book from online bookstores such as Amazon or barnes.

As someone said - Leave the C/C++ programming to system engineers who write operating system, device drivers and fast response real-time programming, you should use Java/PHP-scripting as speed of the computers in year 2005 will be several billion times faster than computers of year 2002!! Hardware is getting cheaper and faster.

1.1 Program in C++ ? C++ vs. Java/PHP

C++ is one of the most powerful languages and will be used for a long time in the future in spite of emergence of Java or PHP-scripting. Programs which need real-time ultra fast response use C/C++. C++ runs extremely fast and is in fact 10 to 20 times FASTER than Java. Java is the "offspring" of C++. The only complaint against Java is - "Java is GOD DAMN SLOW" . Java byte-code is slower when running in a VM than the equivalent natively compiled code. Java runs faster with JIT (Just-In-Time) compiler, but it is still slower than C++. And optimized C/C++ program is about 3 to 4 times faster than Java compiled to native code with JIT compiler or ahead-of-time compiler!! Then, why do people use Java? Because it is pure object oriented and is easier to program in Java, as Java automates memory management, and programmers do not directly deal with memory allocations. This document attempts 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 the Java language.

Because of manual memory allocations, debugging the C++ programs consumes a major portion of time. This document will give you some better ideas and tips to reduce the debugging time.

When should you use C++ and when you should use Java/PHP?

Bottom line is, you use C++:

  • If you are developing a program where speed and performance is very important.
  • If the user base of your application or program is very large. Since C++ involves compile-link-debug cycle it is more time consuming to develop application in C++. You can justify the cost only if the user base of your program is large enough. Linking large number of object files to create an executable takes time. (You can use archives, libraries or shared libraries to reduce linking time).
  • If you have lot of experience programming in C++.

Use Java/PHP:

  • If speed and performance is not important (relative to C/C++).
  • Lower cost of development - There is no compile-link cycle, Java/PHP development is faster than C++.
  • Need rapid development.
  • You want no code maintenance nightmare. Maintaining C++ is more difficult than Java or PHP-scripting.
  • Java and PHP-scripting is the future, hardware speed will be zooming with the introduction of molecular, atomic and sub-atomic scale computers. Future computers will be several trillion times

faster than today's computer. Runtime performance of Java or PHP-script becomes less important as speed of hardware zooms in future. The computers you are using today (as of year 2002) are extremely slow and crawling and are not fast enough.

NOTE: There are lot of improvements in Java compilers (JIT and ahead-of-time). Java programs can be compiled with GNU GCJ http://gcc.gnu.org/java, GCJ is a portable, optimizing, ahead-of-time compiler for the Java programming language. It can compile - Java source code directly to native machine code, Java source code to Java bytecode (class files), and Java bytecode to native machine code.

The Java native code compiler "gnu GCJ" is very rapidly maturing and in near future everybody will be programming in Java instead of C++. Special optimizers in gnu GCJ compiler can make Java programs as fast as C++ programs. The gnu GCJ compiler is 2-3 years away in becoming the defacto compiler on all platforms (initially on Linux and then on MS Windows).

GCJ resources:

1.2 Which one Ada95, C, C++, Java or PHP?

Language choice is very difficult. There are too many parameters - people, people skills, cost, tools, politics (even national politics) and influence of businessmen/commercial companies. The best language based on technical merits does not get selected simply due to political decisions!

See the language comparison chart of David Wheeler at Ada comparison chart. Ada got 93%, Java 72%, C++ 68% and C got 53%. C++ and Java are closer in points (only 4% difference). Development costs of Ada is half of C++ as per Stephen F. Zeigler. Ada95 is available at -

The C++ compiler is lot more complex than a C compiler and C++ programs may run bit slower than C programs. The C compiler is very mature and seasoned.

On some system, you can use compiler options, to optimize the code generated.

Nowadays, C is primarily used for low level systems programming to develop operating systems, device drivers and applications which must perform fast.

Note: Using the String, !StringBuffer?, !StringTokenizer? and !StringReader? classes given in this howto, you can code in C++ which "exactly" looks like Java. Parts of this document tries to close the gap between C++ and Java, by imitating Java classes in C++. Java programmers who jump to and fro from C++ to Java will like this String class.

If you want to bypass the edit-compile-debug-compile cycle of C++ then see scripting languages like PHP which can be used for web development and for general purpose programming. Scripting languages like PHP, PERL enable rapid application development. PHP has some features of object-oriented programming. PHP is at http://www.linuxdoc.org/HOWTO/PHP-HOWTO.html.

1.3 Problems facing the current C++ compilers

Since C++ is super-set of C, it has all the "bad" features of C. Manual allocation and deallocation of memory is tedious and error prone (see Garbage Collector for C++).

In C programming - memory leaks, memory overflows are very common due to usage of features like -


Datatype char * and char[? String functions like strcpy, strcat, strncpy, strncat, etc.. Memory functions like malloc, realloc, strdup, etc..


The usage of char * and strcpy causes horrible memory problems due to "overflow", "fence past errors", "memory corruption", "step-on-others-toe" (hurting other variable's memory locations) or "memory leaks". 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 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 program crashes. The memory bugs due to usage of char * and pointers in C/C++ is costing $2 billion every year in time lost due to debugging and downtime of programs. If you use char * and pointers 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. Give preference in the following order -

  1. Use references instead of pointers.
  2. Java style String class (given in this HOWTO) or the string class from the Standard C++ Library.
  3. Character pointers (char *) in C++ limit the usage of char * to cases where you cannot use the String class.
  4. Character pointers (char *) in C using extern linkage specification, if you do not want to use (char *) in C++.

To use "C char *", you would put all your C programs in a separate file and link to C++ programs using the linkage-specification statement extern "C" -


extern "C" {

  1. include <some_c_header.h>

} extern "C" {

comp(); some_c_function();

}


The extern "C" is a linkage specification and is a flag that everything within the enclosing block (brace-surrounded) uses C linkage, not C++ linkage.

The 'String class' utilizes the constructor and destructor features to automate memory management and provides access to functions like ltrim, substring, etc..

See also related string class in your C++ compiler. The string class is part of the Standard C++ Library library and provides many string manipulation functions.

Because the C++ 'string class' and 'String class' 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'.

Both string classes does everything that char * or char [? does. One of the added benefits is that you do not have to worry about the memory problems and memory allocation at all.


2. Recommended C++ Compilers

The current C++ standard adopted by ISO and ANSI was first finalized in 1997, this means that not all compilers are up to pace yet, and not supporting all features - it is extremely important that you get a standard compliant C++ compiler.

2.1 Compilers for MS Windows 2000/NT/95/98/ME/XP

Since MS Windows is quite popular for C++ development, the String class library given in this document works well and runs very well on all the versions of MS Windows i.e. MS Win XP/2000/NT/95/98/ME. The C++ compilers for MS Windows are:

The String class in this document is tested with all the above compilers. It works fine with MS Visual C++ compiler v6.0, Borland C++ v5.2, Borland C++ compiler v5.5.1 and Bloodshed compiler.

2.2 Compilers for UNIX systems and clones

In a GNU world, you will always be best off with GCC (GNU Compiler Collection), GCC is distributed with most Linux distributions, FreeBSD and most other UNIX clones. The GCC homepage is located at http://gcc.gnu.org. The latest version of GCC (3.0) is one of the most standards compliant compilers out there.


3. String Class Varieties

The string class is the one of the most vital objects in programming, and string manipulations are most extensively used. There is a lot of varieties of string classes. Of course, you can build your own string class by simply inheriting from these string classes -

  • String class given in this document

Appendix A String.h

*

  • Standard C++ Library string class (ANSI/ISO string class at

http://www.msoe.edu/eecs/cese/resources/stl/string.htm and http://www.sgi.com/tech/stl/basic_string.html

*

  • The external library Qt, has a Qt String class at

http://doc.trolltech.com/qstring.html mirror at http://www.cs.berkeley.edu/dmartin/qt/qstring.html

*

  • If none of these 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.) *

3.1 Multiple Inheritance - Sample Custom String class

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 the standard C++ library string class and the String class presented in Appendix A.

Start by downloading the sample file 'string_multi.h' from Appendix A .

That file is reproduced below:


// ****************************************************************** // Sample program to demonstrate constructing your own string class // by deriving from the String class and stdlib's "string" class // ******************************************************************

  1. ifndef __STRING_MULTI_H_ALDEV_
  2. define __STRING_MULTI_H_ALDEV_
  3. include <string>
  4. include "String.h"
  5. include "!StringBuffer?.h"
  6. ifdef NOT_MSWINDOWS
  7. else

using namespace std; // required for MS Visual C++ compiler Version 6.0

  1. endif

// 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 };

  1. endif // __STRING_MULTI_H_ALDEV_


4. Download String

All the programs, examples are given in Appendix of this document. You can download as a single tar zip, the String class, libraries and example programs from

* Go to http://www.milkywaygalaxy.freeservers.com and click on "Source code C++ Programming howto" ( Milkyway Galaxy site)

*

  • Mirror sites are at -

angelfire, geocities, virtualave, 50megs, theglobe, NBCi, Terrashare, Fortunecity, Freewebsites, Tripod, Spree, Escalix, Httpcity, Freeservers.

*

4.1 How Can I trust Al Dev's String Class?

You may a have question of mis-trust on the String class software. To build confidence, there is a scientific method to verify the functionality of Al Dev's String class. In modern days, computer scientists use the CPU power instead of human brain power to verify and validate the software. Human brain is too slow and hence it is better to use the computer's power to test and validate software.

The program example_String.cpp go here and click on 'Source code for C++'. (and also given in Appendix A ) has regression test module which you can use to run the regression tests several millions of times automatically. After running the regression tests on the String class you can certify that the String class program is a ROCK SOLID and a BULLET-PROOF program.

I tested the String class with repeat cycle = 50000 and it ran and completed the program without crash. While it is running I did not notice any memory leak. On Linux, I used /usr/bin/gtop, UNIX top command, KDEStart->System->KDE System Guard and KDEStart->System->Process management to monitor the cpu and memory usage.

I recommend that you start the regression test with repeat cycle equal to 10 million or greater. The greater the repeat cycle number the greater will be your confidence!! Start the test and go to lunch (or go drink gharam chai - "chai peeke auvo") and come back to see the results!!


5. Usage of String class

Take notice, this String class is not the same as the string class implemented in the Standard C++ Library. This special String class is a "home-made" String class, made to help Java programmers convert to C++. When you are more comfortable with C++, you should use the real string class provided in The Standard C++ Library.

To use String class, you should first refer to a sample program "example_String.cpp" given in Appendix A and the String class which is given in Appendix A.

The 'String class' is a complete replacement for char and char * datatype. You can use 'String class' just like char and get much more functionalities. You should link with the library 'libString.a' which you can build from the makefile given in Appendix A and copy the library to /usr/lib or /lib directory where all the C++ libraries are located. To use the 'libString.a' compile your programs like -


g++ example.cpp -lString


See illustration sample code as given below -


String aa; aa = "Creating an Universe is very easy, similar to creating a baby human."; // You can use aa.val() like a 'char *' variable in programs for (unsigned long tmpii = 0; tmpii < aa.length(); tmpii++) { //fprintf(stdout, "aa.val()[%ld?%c ", tmpii, aa.val()[tmpii?); fprintf(stdout, "aa[%ld?=%c ", tmpii, aa[tmpii?); } // Using pointers on 'char *' val ... for (char *tmpcc = aa.val(); *tmpcc ! 0; tmpcc++) { fprintf(stdout, "aa.val()=%c ", *tmpcc); }


5.1 Operators

The 'String class' provides these operators :-

  • Equal to ==

*

  • Not equal to !=

*

  • Assignment =

*

  • Add to itself and Assignment +=

*

  • String concatenation or addition +

*

For example to use operators -


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 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;


5.2 Functions

The functions provided by String class has the same name as that of Java language's String class. The function names and the behaviour is exactly same as that of Java's String class. !StringBuffer? class is also provided. This will facilitate portability of code between Java and C++ (you can cut and paste and do minimum changes to code). 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.

For example to convert integer to string do -


String aa; aa = 34; // The '' operator will convert int to string cout << "The value of aa is : " << aa.val() << endl; aa = 234.878; // The '' operator will convert float to string cout << "The value of aa is : " << aa.val() << endl; aa = 34 + 234.878; cout << "The value of aa is : " << aa.val() << endl; // The output aa will be '268.878' // You must cast String to convert aa = (String) 34 + " Can create infinite number of universes!! " + 234.878; cout << "The value of aa is : " << aa.val() << endl; // The output aa will be '34 Can create infinite number of universes!! 234.878'


Refer to Appendix A String.h for details about the String class function names. The same file String.h is reproduced here in next section.

5.3 Renaming the String class

Case 1: Simple rename

If you do not like the String class name then you can use "typedef" to rename the String class.

In all the files where you do include String.h, insert these lines:


// If you do not like the class name String, then you can rename using typedef typedef String !StringSomethingElseIwant?; // Your remaining code may be like this .... int main() {

StringSomethingElseIwant? aa_renstr;

aa_renstr = "I renamed the String Class using typedef"; // .......etc... }


See the example_String.cpp click on 'Source code for C++'.

Case 2: Resolve conflict

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:


  1. define String String_somethingelse_which_I_want
  2. include "String.h"
  3. undef String
  4. include "!ConflictingString?.h" // This also has String class...

// All your code goes here... int main() { String_somethingelse_which_I_want aa; String bb; // This string class from conflicting string class aa = " some sample string"; bb = " another string abraka-dabraka"; ....... }


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.


6. String.h file

C++ and Java is often used concurrently in many software projects. Programmers jump back and forth between C++ and Java will find this string class very helpful.

In C++ (or any object oriented language), you just read the "class data-structure" (i.e. interface) to begin using that class. 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 understand the String class in String.h file. You do not need to read the entire implementation (String.cpp) in order to use String class. The object oriented classes are real time saver and they very neatly hide the implementation.

(In object oriented Java language there is the equivalent called 'interface' , which hides the implementation details.)

Given below is String.h file and see also Appendix A String.h


// // Author : Al Dev Email: alavoor[AT?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 * //

  1. ifndef __STRING_H_ALDEV_
  2. define __STRING_H_ALDEV_

// do not use iostream as program becomes bulky..

  1. ifdef NOT_MSWINDOWS
  2. include <iostream>
  3. else
  4. include <iostream.h> // For backward compatibility. Standard C++ Library headers have no .h
  5. endif // NOT_MSWINDOWS
  6. include <stdio.h> // for FILE and sprintf()

//#include <list.h> // for list // For MS Windows 95 VC++ or Borland C++ compiler do - //see file d:\program files\CBuilder\include\examples\stdlib\list.cpp and include\list.h //#include <list> // for list //using namespace std; const short INITIAL_SIZE = 50; const short NUMBER_LENGTH = 300; const int MAX_ISTREAM_SIZE = 2048; //class !StringBuffer?; // I compiled and tested this string class on Linux (Redhat 7.1) and // MS Windows Borland C++ version 5.2 (win32). This should also work // using MS Visual C++ compiler class String { public: String(); String(const char bb[?); // needed by operator+ String(const char bb[?, int start, int slength); // subset of chars 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 - but causes compile problem on MS windows and core dumps 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. char val() {return sval;} // It is not safe to make sval public // Functions below imitate Java language's String object unsigned long length(); 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 concat(int bb); String concat(unsigned long bb); String concat(float bb); String concat(double bb); 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); // Directly changes object. dummy to get different signature String rtrim(); void rtrim(bool dummy); // Directly changes object. See also chopall(). // dummy to get different signature void chopall(char ch'\n'); // removes trailing character 'ch'. See also rtrim() 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); void explode(char *separator); // see also token() and overloaded explode() String *explode(int & strcount, char separator = ' '); // see also token() 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(); String token(char separator = ' '); // see also !StringTokenizer?, explode() 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); // Directly changes object void reverse(bool dummy); // Directly changes object. dummy to get different signature String deleteCharAt(int loc, bool dummy); // Directly changes object String deleteStr(int startIndex, int endIndex, bool dummy); void trim(bool dummy); // Directly changes object. dummy to get different signature String insert(int index, String str2); String insert(int index, String str2, bool dummy); // Directly changes object String insert(int index, char ch); String insert(int index, char ch, bool dummy); // Directly changes object String insert(char *newstr, int start = 0, int length = 0, char padchar = ' '); String dump(); // Dump the string like 'od -c' (octal dump) does // required by Java's !StringBuffer? void ensureCapacity(int capacity); void setLength(int len); void setCharAt(int where, char ch); // see also charAt(), getCharAt() // 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(); } char * number2string(int bb); // see also String(int) char * number2string(long bb); // see also String(long) char * number2string(unsigned long bb); // see also String(long) char * number2string(double bb); // see also String(double) /////////////////////////////////////////////// // 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() // String split(char separator = ' '); // Use token(), explode() or !StringTokenizer? class 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(), explode() or !StringTokenizer? class // begin(); iterator. Use operator [ii? // end(); iterator. Use operator [ii? // copy(); Use assignment = operator, String aa = bb; // clone(); Use assignment = operator, String aa = bb; // void putCharAt(int where, char ch); Use setCharAt() // void replaceCharAt(int where, char ch); Use setCharAt() // char getCharAt(int where); Use !CharAt?() // void parseArgs(int where, char ch); Use !StringTokensizer? class, token() or explode() // void truncate(); Use trim(), rtrim(), chop() or chopall() // convert number to string notostring(), int2str, long2str Use number2string() // 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); bool String::operator< (const char *rhs) const; // handy methods for map & vector: bool String::operator< (const String & rhs) const; // handy methods for map & vector: //do later: static list<String> explodeH; // list head protected: char *sval; // Not safe to make sval public void verifyIndex(unsigned long index) const; // not "inline" because MS Win32 complains void verifyIndex(unsigned long index, char *aa) const;// not "inline" - MS Win32 complains void _str_cat(char bb[?); void _str_cat(int bb); void _str_cat(unsigned long bb); void _str_cat(float bb); void _str_cpy(char bb[?); void _str_cpy(int bb); // itoa void _str_cpy(unsigned long bb); void _str_cpy(float bb); // itof 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); bool _equalto(const String & rhs, bool type = false); bool _equalto(const char *rhs, bool type = false); String *_pString; // temporary pointer for internal use.. char *_pNumber2String; // temporary pointer for internal use.. inline void _allocpString(); inline void _allocpNumber2String(); inline void Common2AllCstrs(); 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); void _roundno(double input_dbl, float input_flt, short precision, bool type); }; // Global variables are defined in String.cpp

  1. endif // __STRING_H_ALDEV_

6.1 !StringBuffer?.h

C++ and Java is often used concurrently in many software projects. Programmers jump back and forth between C++ and Java will find this stringbuffer class very helpful.


// // Author : Al Dev Email: alavoor[AT?yahoo.com //

  1. ifndef __STRINGBUFFER_H_ALDEV_
  2. define __STRINGBUFFER_H_ALDEV_

// 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?();

StringBuffer?(char *aa);

StringBuffer?(int size);

StringBuffer?(String str);

int capacity();

StringBuffer? append(String str2);

// See also operator + //{ *this += str2; return *this;} // This is causing core dumps...

StringBuffer? append(char *str2);

StringBuffer? append(int bb);

StringBuffer? append(unsigned long bb) ;

StringBuffer? append(float bb) ;

StringBuffer? append(double bb) ;

StringBuffer? insert(int index, String str2);

StringBuffer? insert(int index, char ch);

StringBuffer? reverse();

// Java's "delete()". Cannot use name delete in C++

StringBuffer? deleteStr(int startIndex, int endIndex);

StringBuffer? deleteCharAt(int loc);

StringBuffer? substring(int startIndex, int endIndex = 0);

void assign(char *str); private:

StringBuffer? *_pStringBuffer;

inline void allocpStringBuffer(); inline void Common2AllCstrs(); };

  1. endif // __STRINGBUFFER_H_ALDEV_

6.2 !StringTokenizer?.h

C++ and Java is often used concurrently in many software projects. Programmers jump back and forth between C++ and Java will find this stringtokenizer class very helpful.


// // Author : Al Dev Email: alavoor[AT?yahoo.com //

  1. ifndef __STRINGTOKENIZER_H_ALDEV_
  2. define __STRINGTOKENIZER_H_ALDEV_

// 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 delimAsToken);

!StringTokenizer?(); int countTokens(); bool hasMoreElements(); bool hasMoreTokens(); String nextElement(); // in Java returns type 'Object' String nextToken(); String nextToken(String delimiters); private: int !CurrentPosition?; // current index on string int !TotalTokens?; int !RemainingTokens?; char * !ListOfDl?; // list of delimiters char * !WorkStr?; // temp work string char * !OrigStr?; // original string passed bool !DlFlag?; // delimiter flag inline void vPrepWorkStr(char *delimiters = NULL); };

  1. endif // __STRINGTOKENIZER_H_ALDEV_


7. The Standard C++ Library string class

While the previously mentioned String class (note the uppercase S), is a good thing for people coming from Java, then you should take notice of the "real" string class provided by The Standard C++ Library.

The string class was made to overcome one of the greatest pitfalls in C; character arrays. While character arrays are extremely fast, they have many bad sides. Character arrays is the cause of many bugs, and parsing character arrays is very time consuming.

The string class brings a good interface for parsing and handling strings, and it's even STL compatible, so it can be used with all the general STL algorithms. Actually you could say that a string is a vector<char>. A container of chars, or an advanced array of chars.

Useful string reference can be found at the following sites:

  • SGI STL basic_string reference:

http://www.sgi.com/tech/stl/basic_string.html. *

7.1 string by example

Creating a string is easy:


  1. include <string>
  2. include <iostream>

using namespace std; int main() { string str("Hello World!"); // Or string str = "Hello World!"; cout << str << endl; }


This code will create a string called "str', and put "Hello World!' into it. It is then being outputted to standard output by using cout.

(Note that I will skip the headers and the namespace from now on.)

Taking a substring of a string is also easy:


string str("Hello Universe!"); string start = str.substr(0, 5); string end = str.substr(5)?;


This will put the first 6 characters into the string "start", and the rest into "end".

To get the size or length of a string, you would simply do this:


string str("How long is this string?"); cout << "Length of string is: " << str.size() << endl;


You can also use length() which works exactly the same.

7.2 Searching a string

Searching a string is much easier than using plain character arrays, the string class provides efficient member functions to search through the string. All member functions return string::size_type.

Member function Purpose find() find the first position of the specified substring find_first_of() equal to find(), but finds the first position of any character specified find_last_of() equal to findthinspfirstthinspof(), but finds the last position of any character specified find_first_not_of() equal to findthinspfirstthinspof(), but returns the position of the first character not of those specifed find_last_not_of() equal to findthinsplastthinspof(), but returns the last position of any characters not specified rfind() equal to find(), but searches backwards string search member functions

A very common thing to do, is to search a string for contents. This can be done by using find()


string str("Hello, can you find Ben?"); string::size_type position = str.find("Ben"); cout << "First occurence of Ben was found at: " << position << endl;


This code make a case sensitive search for 'Ben' in the string, and put the start position in the variable 'position' of type string::size_type. Note that the return value is not an int, but a string::size_type which is a special implementation defined integral value.

The member function find_first_of() needs a practical introduction, consider this:


string s = "C++ is an impressive language."; string::size_type pos = s.find_first_of(" ."); while (pos != string::npos) { cout << "Found space or dot at: " << pos << endl; pos = s.find_first_of(" .", pos + 1); }


By using find_first_of(), we can search the string for any character of the first argument, here we decide to search for a space or a dot.

Try compiling the program and check the output.

7.3 A string tokenizer

A very common operation with strings, is to tokenize it with a delimiter of your own choice. This way you can easily split the string up in smaller pieces, without fiddling with the find() methods too much. In C, you could use strtok() for character arrays, but no equal function exists for strings. This means you have to make your own. Here is a couple of suggestions, use what suits your best.

The advanced tokenizer:


void Tokenize(const string& str, vector<string>& tokens, const string& delimiters = " ") { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } }


The tokenizer can be used in this way:


  1. include <string>
  2. include <algorithm>
  3. include <vector>

using namespace std; int main() { vector<string> tokens; string str("Split me up! Word1 Word2 Word3."); Tokenize(str, tokens); copy(tokens.begin(), tokens.end(), ostream_iterator<string>(cout, ", ")); }


The above code will use the Tokenize function, take the first argument str and split it up. And because we didn't supply a third parameter to the function, it will use the default delimiter " ", that is - a whitespace. All elements will be inserted into the vector tokens we created.

In the end we copy() the whole vector to standard out, just to see the contents of the vector on the screen.

Another approach is to let stringstreams do the work. streams in C++ have the special ability, that they read until a whitespace, meaning the following code works if you only want to split on spaces:


  1. include <vector>
  2. include <string>
  3. include <sstream>

using namespace std; int main() { string str("Split me by whitespaces"); string buf; // Have a buffer string stringstream ss(str); // Insert the string into a stream vector<string> tokens; // Create vector to hold our words while (ss >> buf) tokens.push_back(buf); }


And that's it! The stringstream will use the output operator (>>) and put a string into buf everytime a whitespace is met, buf is then used to push_back() into the vector. And afterwards our vector tokens will contain all the words in str.


8. File Class

C++ and Java is often used concurrently in many software projects. Programmers jump back and forth between C++ and Java will find this File class very helpful.

You would use the File class to manipulate the operating system files. This class is an imitation of Java's File class and will be very useful in C++ programming. Using this File class in C++ you can do if file exists() ?, if directory exists() ?, file length() and other functions.

Note that these classes has some great functionality not supported in The Standard C++ Library, but don't confuse them with fstreams(iostreams), which is the way you should perform many other operations on files.

  • C++ File class is at

File.h http://www.angelfire.com/country/aldev0/cpphowto/File.h and File.cpp File.cpp click on 'Source code of C++'. *

  • Java: Java.io.File class definition

http://java.sun.com/j2se/1.3/docs/api/java/io/File.html *

  • Quick Reference on File Class

http://unicornsrest.org/reference/java/qref11/java.io.File.html *


9. Memory Allocation in C++

In C, you use malloc(), free() and variants of malloc() to allocate and free memory, but these functions have their pitfalls. Therefor C++ introduced operators for handling memory, these operators are called new and delete. These operators allocates and frees memory from the heap (or sometimes called the free store) at runtime.

In C++, you should always use new and delete unless you're really forced to use malloc() and free(). But be aware that you cannot mix the two. You cannot malloc() memory, and then delete it afterwards, likewise you can't "new" memory, and then free it with free().

9.1 C++ Zap (Delete) function

The delete and new operators in C++ are much better than the malloc and free functions of C. Consider using new and zap (delete function) instead of malloc and free as much as possible.

To make delete operators even more cleaner, make a Zap() inline function. Define a zap() function like this:


// Put an assert to check if x is NULL, this is to catch // program "logic" errors early. Even though delete works // fine with NULL by using assert you are actually catching // "bad code" very early // Defining Zap using templates // Use zap instead of delete as this will be very clean template <class T> inline void zap(T & x) { {assert(x != NULL);} delete x; x = NULL; } // In C++ the reason there are 2 forms of the delete operator is - because // there is no way for C++ to tell the difference between a pointer to // an object and a pointer to an array of objects. The delete operator // relies on the programmer using "[?" to tell the two apart. // Hence, we need to define zaparr function below. // To delete array of pointers template <class T> inline void zaparr(T & x) { {assert(x != NULL);} delete [? x; x = NULL; }


The zap() function will delete the pointer and set it NULL. This will ensure that even if multiple zap()'s are called on the same deleted pointer then the program will not crash. Please see the function zap_example() in example_String.cpp click on 'Source code of C++'.


// See zap_example() in example_String.cpp zap(pFirstname); //zap(pFirstname); // no core dumps. Because pFirstname is NULL now //zap(pFirstname); // no core dumps. Because pFirstname is NULL now zap(pLastname); zap(pJobDescription); int *iiarray = new int[10?; zaparr(iiarray);


There is nothing magical about this, it just saves 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. 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 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. For an example, see the file "String.h" which is using the my_malloc() and my_free() functions.

WARNING : Do not use free() to free memory allocated with 'new' or 'delete' to free memory allocated with malloc. If you do, then results will be unpredictable.

See the zap examples in example_String.cpp click on 'Source code of C++'.

9.2 Usage of my_malloc and my_free

Try to avoid using malloc and realloc as much as possible and use new and zap(delete). But sometimes you may need to use the C style memory allocations in C++. Use the functions my_malloc() , my_realloc() and my_free(). 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 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.


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); // 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; }


See my_malloc.cpp. and the header file my_malloc.h. for full implementation of the my_malloc program.

An example on usage of my_malloc and my_free as below:


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);


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*.

9.3 Garbage Collector for C++

In C/C++ Garbage Collection is not a standard feature and hence allocating and freeing storage explicitly is difficult, complicated and is error-prone. The Garbage Collection (GC) is not part of the C++ standard because there are just so many ways how one could implement it; there are many GC techniques, and deciding to use a particular one would not be good for certain programs. Computer scientists had designed many GC algorithms, each one of them catering to a particular problem domain. There is no one single generic GC which will tackle all the problem domains. As a consequence, GC is not part of C++ standard, they just left it out. Still, you always have the choice of many freely available C++ libraries that do the job for you.

Visit these sites:

* Garbage Collection *

* Memory management *

  • Java-like library - Hans-J. Boehm's garbage

collector at Hans-Boehm works quite well under linux, solaris and windows. *


10. Pointers are problems

Pointers are not required for general purpose programming. In modern languages like Java there is no support for pointers (Java internally uses pointers). Pointers make 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 great pain. It is possible to write an application without using pointers. You should pointers only in those cases where references will not work.

A reference 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.

Syntax of References: Declare a reference by writing the type, followed by the reference operator (&), followed by the reference name. References MUST be initialized at the time of creation. For example -


int weight; int & rweight = weight; DOG aa; DOG & rDogRef = aa;


Do's of references -

  • Do use references to create an alias to an object

*

  • Do initialize all references

*

  • Do use references for high efficiency and performance of program.

*

  • Do use const to protect references and pointers whenever possible.

*

Do not's of references -

  • IMPORTANT: Don't use references to NULL objects

*

  • Don't confuse the address of operator & with reference operator. The references

are used in the declarations section (see Syntax of References above). *

  • Don't try to reassign a reference

*

  • Don't use pointers if references will work

*

  • Don't return a reference to a local object

*

  • Don't pass by reference if the item referred to may go out of scope

*


11. Debugging

Finding the exact source to a bug can be a troublesome process, however there is several techniques used for debugging:

  • Printing to standard out - for simple cases, print the values of

several variables, see what they contain - and find out where exactly your program crashes *

  • Using a debugger, a debugger lets you set breakpoints, and make

backtraces in your code, while it's running. Most IDEs come with a debugger, for GNU systems there is gdb. *

  • Use compiler features, on most compilers you can enable more warnings,

for example on g++, use -Wall *

Sites to help debugging:

  • Debugging C and C++ in a UNIX enironment:

http://www.liacs.nl/jdassen/onderwijs/stuva/debug/debug.html *

  • MPatrol - a useful memory debugging tool:

http://www.cbmamiga.demon.co.uk/mpatrol *

  • NJAMD - another useful memory debuggging tool:

http://sourceforge.net/projects/njamd/ *

  • LeakTracer? - a simple yet powerful tool to find memory leaks:

http://www.andreasen.org/!LeakTracer/ *

11.1 Debug files

To debug any C++ or C programs include the file 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 debug.cpp for implementation of debug routines.

And see the file my_malloc.cpp for a sample which uses debug.h and debug functions.

See the sample Makefile .


12. IDE's and editors for C++

When programming C++, it is a good idea to used to an editor or an IDE. Most programmers have their own favourites, and it's a religious discussion on which is better.

You can choose to use an IDE (Integrated Development Environment), which is an application with embedded editor, compiler, documentation and more. And then there is the standalone editors, which some people likes better.

12.1 IDE's

The following IDE tools (Integrated Development Environment) are available for C++:

  • The "top rated" Dev-C++ is an full-featured Integrated Development Environment (IDE)

for both Win32 and Linux. It uses GCC, Mingw or Cygwin as compiler and libraries set. It is at http://www.bloodshed.net/devcpp.html and at mirror-site *

  • KDE KDevelop

Kdevelop *

  • Blatura site

C++ Tools *

  • Amulet

Amulet *

  • App Dev suite

Angoss *

  • Make replacement

Brass *

  • S/W product metrics

CCC *

  • Project mgmt, edit, compile, debug

C-Forge *

  • Dev environment

Code Crusader *

  • Graphic gdb

Code Medic *

  • Code analysis

CodeWizard?

*

  • Gen HTML, !LaTex? for C++ cod

Doc C++ *

  • GUI toolkit openGL

Ftk *

  • C++ and Java IDE

GLG IDE *

  • HP IDE

HP Eloquence *

  • IDE C++, Java, Pascal

RHIDE *

  • IDE for C++, Java

SNiff *

  • IDE for C++, Java

Wipeout *

  • X-based dev env

XWPE *

12.2 Editors

The problem with IDE's is many times that their editors have a big lack of functionality. Therefor many people wants a powerful editor alone, and then supply with a compiler next to it.

Of powerful editors, vim and emacs can be mentioned. They are both available for most platforms - and they support syntax highlighting and other things which will make you more efficient.

Other editors include !UltraEdit?(win32 only) and !EditPlus?(win32 only).

  • Vim online at

http://vim.sourceforge.net/ *

  • Vim color text editor for C++, C

http://www.linuxdoc.org/LDP/HOWTO/Vim-HOWTO.html *

  • Emacs at

http://www.gnu.org/software/emacs/ *

  • EditPlus? for Windows at

http://www.editplus.com/ *

  • UltraEdit? for Windows at

http://www.ultraedit.com/ *

12.3 Other ressources

  • C++ Beautifier HOWTO

http://www.linuxdoc.org/LDP/HOWTO/C-C++Beautifier-HOWTO.html *

  • Source code control system for C++ programs (CVS HOWTO)

http://www.linuxdoc.org/LDP/HOWTO/CVS-HOWTO.html *

  • Linux goodies main site is at

http://www.milkywaygalaxy.freeservers.com Mirror sites are at - angelfire, geocities, virtualave, 50megs, theglobe, NBCi, Terrashare, Fortunecity, Freewebsites, Tripod, Spree, Escalix, Httpcity, Freeservers. *


13. C++ Online Textbooks and Docs

There are MORE THAN ONE MILLION online articles/textbooks/reference guides on C++ language. That is because C++ is used extensively for a very long period of time. You can find them using the Internet search engines like Google, Yahoo, Lycos, Excite etc..

  • "C++ Annotations" online book main site:

Annotations *

  • "Teach Yourself C++ in 21 days" online textbook

Teach C++ *

  • C++ Textbook by Bruce Eckel

Thinking in C++ *

  • C++ Open books:

Panorama and click on Open Books. *

  • "Who's Afraid of C++?" online textbook:

Steveheller *

  • "Introduction to Object Oriented Programming" an ebook

C++ OOP *

  • C++ in Hypertext

C++ Hypertext *

  • Object Oriented Systems

OOP article

*

  • C++ Language Reference from cplusplus.com

http://www.cplusplus.com/ref

*

  • C++ Documentation from cplusplus.com

http://www.cplusplus.com

*

  • Common C++ Pitfalls to be avoided

http://www.horstmann.com/cpp/pitfalls.html

*

  • Porting C++ to Java

PortingC *

  • C/C++ Journals

UtahJournals?

*

  • Yahoo C++ category site

CCyahoo *

  • C Library Reference Guide

c_guide *

  • Online textbooks C++/Java

FreeLib?

*

  • "C++ In Action" by Bartosz Milewski at

http://www.relisoft.com/book/index.htm *

  • Amusing examples of how not to write code. "How to write unmaintainable code"

at http://mindprod.com/unmain.html *

Java books which will be useful for C++ programmers:

  • Great Web reference site

WebRef?

*

  • Many Java books

JBooks *

  • Intro to Java V3.0

JavaNotes

mirror

JavaNotes

*

  • Thinking in Java:

Thinking Java *

  • John Hopkins Univ - Java resources

Hall *

  • online Java tutorial

Chortle *

  • Practical guide for Java

SunBooks?

*

  • Java

Soton *

13.1 C++ Sites

Visit the following C++ sites :-

  • C++ STL basic string class documentation is at

http://www.sgi.com/tech/stl/basic_string.html. *

  • See the section

STL References

*

  • C++ Crash-proof site

http://www.troubleshooters.com/codecorn/crashprf.htm *

  • C++ Memory site

http://www.troubleshooters.com/codecorn/memleak.htm

*

  • GNU Main site

http://www.gnu.org and gnu C++ site at http://gcc.gnu.org *

  • AS University C++ Standard String class

http://www.eas.asu.edu/cse200/outline

*

  • Java JString for C++

http://www.mike95.com/c_plusplus/classes/JString/JString_cpp.asp *

  • C++ Language Reference

http://www.msoe.edu/tritt/cpplang.html *

  • C++ Program examples and samples

http://www.msoe.edu/tritt/cpp/examples.html *

  • Neil's C++ stuff

http://www.cyclone7.com/cpp *

Internet has vast amounts of documentation on C++. Visit the search engines like Google, Yahoo, Lycos, Infoseek, Excite. Type in the keywords 'C++ tutorials' 'C++ references' 'C++ books' . You can narrow down the search criteria by clicking on Advanced search and select search by exact phrase

* http://www.google.com *

* http://www.yahoo.com *

* http://www.lycos.com *

* http://www.infoseek.com *

* http://www.excite.com *

* http://www.mamma.com *

13.2 C++ Tutorials

There are many on-line tutorials available on internet. Type 'C++ tutorials' in the search engine.

  • C++ Tutorial

http://www.xploiter.com/programming/c/index.shtml *

  • Cplusplus.com Tutorial

http://www.cplusplus.com/doc/tutorial *

  • C++ Tutorial IISc, India

http://www.csa.iisc.ernet.in/Documentation/Tutorials/!StyleGuides/c++-style.html *

  • C++ Tutorial Brown Univ

http://wilma.cs.brown.edu/courses/cs032/resources/C++tutorial.html *

  • C++ Tutorial

http://home.msuiit.edu.ph/ddd/tutorials/cpp/cpplist.htm *

  • C++ Tutorial IOstreams

http://osiris.sunderland.ac.uk/cs0pdu/pub/com365/Sched3/iocpp.html *

13.3 Useful links

  • Bird's eye view of C++ URLs (about 153 url links)

http://www.enteract.com/bradapp/links/cplusplus-links.html

*

  • This

URL: http://www.snippets.org portable C code contains over 360 files.

*

  • Mathtools at

http://www.mathtools.net is a technical computing portal for all scientific and engineering needs. The portal is free and contains over 20,000 useful links to technical computing programmers, covering C/C++, Java, Excel, MATLAB, Fortran and others. *

13.4 C++ Quick-Reference

Type 'C++ Reference' in the search engine.

  • C++ quick ref

http://www.cs.jcu.edu.au/david/C++SYNTAX.html *

  • C++ Standard Library Quick Reference

http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html *

  • C++ STL from halper

http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html *

13.5 C++ Usenet Newsgroups

  • C++ newsgroups :

comp.lang.c++.announce *

  • C++ newsgroups :

comp.lang.c++.* *

  • C++ newsgroups :

http://marshall-cline.home.att.net/cpp-faq-lite *

13.6 Java like API

Visit the following sites for Java like API for C++

  • Java utils in C++

http://www.pulsar.org/users/ej/archive/oop *

  • PhD Thesis book Java API in C++

http://www.pulsar.org/archive/phd/ejphd *

  • Java-like library Jakelib at

http://www.jakelib.org. The version 2 of Jakelib uses Boehm's gc and is a lot more Java-like. Written by Florian. *


14. C++ Coding Conventions

Coding convention is very essential for readability and maintenance of programs. And it also greatly improves the productivity of the programmer. Coding convention is required for good coding discipline. The following is suggested - inside class definition:

  • All public variables must begin with m like mFooVar.

The m stands for member. *

  • All protected variables must begin with mt,

like mtFooVar and methods with t, like tFooNum(). The t stands for protected. *

  • All private variables must begin with mv, like mvFooVar and

methods with v, like vFooLone(). The v stands for private. *

  • All public, protected and private variables must begin with

uppercase after m like F in mFooVar. *

  • All pointer variables must be prefixed with p, like

    • Public variables mpFooVar and methods like !FooNum?()

    *

    • Protected variables mtpFooVar and methods with t like tFooNum()

    *

    • Private variables mvpFooVar and methods with v like vFooNum()

    *

*

Uniform world-wide coding convention for C++ language will help better programming.

In the sample code given below t stands for protected, v stands for private, m stands for member-variable and p stands for pointer.


class !SomeFunMuncho? { public: int mTempZimboniMacho; // Only temporary variables should be public as per OOP float *mpTempArrayNumbers; int !HandleError?(); float getBonyBox(); // Public accessor as per OOP design float setBonyBox(); // Public accessor as per OOP design protected: float mtBonyBox; int *mtpBonyHands; char *tHandsFull(); int tGetNumbers(); private: float mvJustDoIt; char mvFirstName[30?; int *mvpTotalValue; char *vSubmitBars(); int vGetNumbers(); };


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 mvFirstName you can tell that it is member of a class and is a private variable.

Visit the C++ Coding Standards URLs

  • C++ FAQ Lite - Coding standards

http://www.parashift.com/c++-faq-lite/coding-standards.html *

  • Rice university coding standard

http://www.cs.rice.edu/dwallach/CPlusPlusStyle.html *

  • Identifiers to avoid in C++ Programs

http://oakroadsystems.com/tech/cppredef.htm *

  • Coding standards from Possibility

http://www.possibility.com/Cpp/!CppCodingStandard.html and mirror site *

  • Coding standards for Java and C++ from Ambysoft

http://www.ambysoft.com/!JavaCodingStandards.html *

  • Rules and recommendations

http://www.cs.umd.edu/users/cml/cstyle/ *

  • Indent and annotate

http://www.cs.umd.edu/users/cml/cstyle/indhill-annot.html *

  • Elemental rules

http://www.cs.umd.edu/users/cml/cstyle/Ellemtel-rules.html *

  • C++ style doc

http://www.cs.umd.edu/users/cml/cstyle/Wildfire-C++Style.html *

  • C++ Coding Standards by Brett Scolcum

http://www.skypoint.com/slocum/prog/cppstds.html *

  • Logikos C++ Coding Standards

http://www.logikos.com/standards/cpp_std.html *

  • NRad C++ coding standards

http://cadswes.colorado.edu/billo/standards/nrad *

  • BEJUG C++ coding standards

http://www.meurrens.org/ip-Links/java/joodcs/!ToddHoff.html *

  • Arctic Labs coding standards

http://www.arcticlabs.com/codingstandards

See also

*

  • For rapid navigation with ctags

Vim color text editor *

  • To improve productivity see

C++ Beautifier HOWTO *


15. C++ Scripting Languages

The major disadvantage of C++ is that you must recompile and link the object files to create an executable anytime you make a small change. The compile/link/debug cycles take away a lot of time and is quite unproductive. Since modern CPU's and RAM are becoming extremely fast and cheap, it is sometimes better to spend more money on hardware and use scripting languages for development.

15.1 PIKE & PHP (C/C++ Scripting Languages)

The scripting languages like PHP or PIKE eliminates the linking and re-compiling and will really speed up the development process.

As memory (RAM) prices are dropping and CPU speeds are increasing, scripting languages like PHP or PIKE will EXPLODE in popularity. PHP or PIKE will become most widely used scripting language as it is object oriented and it's syntax is very identical to that of C/C++.

Programming productivity will increase by five times by using the PHP or Pike C++ scripting language. And PHP or PIKE is very useful for 'proof of concept' and developing prototypes rapidly.

PHP is exploding in popularity for general purpose programming and for web development. PHP may become the most widely used scripting language in near future. PHP is at http://www.linuxdoc.org/HOWTO/PHP-HOWTO.html.

The Pike is at http://pike.roxen.com and at 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.

15.2 !SoftIntegration? Ch (C/C++ Scripting Language)

If you want commercial scripting language, get the 'Ch scripting' product from

SoftIntegration? corporation at

http://www.softintegration.com.

The scripting language environment called Ch is a superset of C with high-level extensions, and salient features from C++ and other languages so that users can learn the language once and use it anywhere for almost any programming purposes. This C-compatible scripting language environment is also a middleware serving as crucial software infrastructure for running portable applications in heterogeneous platforms. The portable Ch code can be deployed safely over the internet or intranets to run anywhere ranging from supercomputers, workstations, PCs, Palm Pilots, PDA, to non-traditional computing devices such as CNC machines, robots, TVs, refrigerators, among others.

15.3 PHP (C++ Scripting Language)

PHP is hypertext-preprocessor scripting language and is very rapidly evolving and getting object oriented features. It has the "class" keyword through which it tries to implement object oriented scripting. May be in near future PHP will mature rapidly to become a robust scripting language for object oriented projects. In future it will tackle both the web applications and general purpose applications. Why have different scripting languages for web and general applications, instead just use PHP for both. PHP is at http://www.linuxdoc.org/HOWTO/PHP-HOWTO.html.


16. Templates

Templates is a feature in C++ which enables generic programming, with templates code-reuse becomes much easier.

Consider this simple example:


  1. include <string>
  2. include <iostream>

void printstring(const std::string& str) { std::cout << str << std::endl; } int main() { std::string str("Hello World"); printstring(str); }


Our printstring() takes a std::string as its first argument, therefor it can only print strings. Therefor, to print a character array, we would either overload the function or create a function with a new name.

This is bad, since the implementation of the function is now duplicated, maintainability becomes harder.

With templates, we can make this code re-useable, consider this function:


template<typename T> void print(const T& var) { std::cout << var << std::endl; }


The compiler will automatically generate the code for whatever type we pass to the print function. This is the major advantage of templates. Java doesn't have templates, and therefor generic programming and code reuse is harder in Java.

References:

* http://babbage.cs.qc.edu/STL_Docs/templates.htm Mirror at: http://www.mike95.com/c_plusplus/tutorial/templates

*

  • This tells about #pragma template : -

http://www.dgp.toronto.edu/people/!JamesStewart/270/9697f/notes/Nov25-tut.html

*

  • Very GOOD site:

http://www.cplusplus.com/doc/tutorial/tut5-1.html http://www.cplusplus.com/doc/tutorial

*

  • For certification of C++: goto

http://examware.com and click on "Tutorials" and then C/C++ button

*

  • C++ Open books:

http://www.softpanorama.org/Lang/cpp.shtml and click on tutorials

*

  • Templates tutorial :

http://www.infosys.tuwien.ac.at/Research/Component/tutorial/prwmain.htm *


17. STL References

Please visit the following sites for STL:

  • Very good intro to iterators

http://www.cs.trinity.edu/joldham/1321/lectures/iterators/ *

  • Intro to STL SGI

http://www.sgi.com/tech/stl/stl_introduction.html *

  • Mumits STL Newbie guide (a bit outdated)

http://www.xraylith.wisc.edu/khan/software/stl/STL.newbie.html *

  • ObjectSpace? examples: !ObjectSpace? has contributed over 300 examples to the public domain and these are a very good start for beginners.

ftp://butler.hpl.hp.com/stl/examples.zip *

  • Joseph Y. Laurino's STL page.

http://weber.u.washington.edu/bytewave/bytewave_stl.html *

  • Marian Corcoran's STL FAQ.

ftp://butler.hpl.hp.com/stl/stl.faq *

STL tutorials:

  • Phil Ottewell's STL Tutorial -

http://www.yrl.co.uk/phil/stl/stl.htmlx *

  • Good, but outdated doc -

http://www.decompile.com/html/tut.html Mirror: http://mip.ups-tlse.fr/grundman/stl-tutorial/tutorial.html *

  • The Code Project, introduction to C++/STL/MFC

http://www.codeproject.com/cpp/stlintroduction.asp *

  • C++ Standard Template Library, another great tutorial, by Mark Sebern

http://www.msoe.edu/eecs/cese/resources/stl/index.htm *

  • Technical University Vienna by Johannes Weidl

http://dnaugler.cs.semo.edu/tutorials/stl mirror http://www.infosys.tuwien.ac.at/Research/Component/tutorial/prwmain.htm *

Main STL sites:

  • C++ STL from SGI

http://www.sgi.com/tech/stl *

  • C++ STL from RPI univ

http://www.cs.rpi.edu/projects/STL/htdocs/stl.html *

  • C++ STL site

ODP for STL and the mirrorsite *

  • STL for C++ Programmers

http://userwww.econ.hvu.nl/ammeraal/stlcpp.html *

  • C++ STL from halper

http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html *

17.1 Overview of the STL

The STL offers the programmer a number of useful data structures and algorithms. It is made up by the following components.

  • Containers. There are two types:

    • Sequential. This group comprises the vector, list and deque types.

    *

    • Sorted Associative. This group comprises the set, map, multiset and multimap types.

    *

*

  • Iterators. These are pointer like objects that allow the user to step through the contents of a container.

*

  • 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.)

*

  • 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.

*

  • Adaptors. The STL provides

    • Container adaptors that allow the user to use, say, a vector as the basis of a stack.

    *

    • Function adaptors that allow the user to construct new function objects from existing function objects.

    *

*

  • 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. *

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:


template<class T1, class T2> class pair { public: T1 first; T2 second; pair(const T1& a, const T2& b) : first(a), second(b) {} };


and there is a convenient function make_pair with signature:


pair<T1,T2> make_pair(const T1& f, const T2&,s)


as well as implementations of operator== and operator < . 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 <utility>. It crops up in a number of places but particularly when using the set and map classes.

17.2 Header Files

To use the various bits of the STL you have to #include the appropriate header files. If your compiler is not standard compliant, this may differ, but a standard compliant compiler (like g++), would have these:

  • <vector> for the vector type.

*

  • <list> for the list type.

*

  • <set> for the set type.

*

  • <map> for the map type.

*

  • <algorithm> for access to the generic algorithms.

*

Note that headers in the Standard C++ Library is without a .h suffix. If you use an old or poor compiler, the above headers might fail, if then, you can try the version with the .h suffix, or better yet; get another compiler.

17.3 The Container Classes Interface

The container classes have many member functions that have the same names. These functions provide the same (or very similar) interface 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.

Operation Purpose vector list set map == comparison * *** < 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 first element * Container Class Interface

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.

17.4 Vectors

A vector is an array like container that improves on the C++ array types. In particular it is not necessary 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 push_back function. (In fact the insert function allows you insert new elements at any position of the vector, but this is a very inefficient operation -- if you need to do this often consider using a list instead).

Constructing Vectors

vector 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


vector<int> v1; vector<string> v2; vector<!FiniteAutomaton?> v3;


declares that v1 is a vector that holds integers, v2 a vector that holds strings and v3 holds objects of type !FiniteAutomaton? (presumably an user defined class type). These declarations do not say anything about how large the vectors are to be (implementations will use a default starting size) and you can grow them to as large as you require.

You can give an initial size to a vector by using a declaration like


vector<char> v4(26);


which says that v4 is to be vector of characters that initially has room for 26 characters. There is also a way to initialise a vector's elements. The declaration


vector<float> v5(100,1.0);


says that v5 is a vector of 100 floating point numbers each of which has been initialised to 1.0.

Checking Up on Your Vector

Once you have created a vector you can find out the current number of elements it contains by using the size function. This function takes no arguments and returns an integer (strictly a value of type size_type, 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?


<vector-size.cpp>=

  1. include <iostream>
  2. include <vector>

using namespace std; int main() { vector<int> v1; vector<int> v2(10); vector<int> v3(10,7); cout << "v1.size() returns " << v1.size() << endl; cout << "v2.size() returns " << v2.size() << endl; cout << "v3.size() returns " << v3.size() << endl; }


To check on whether 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)?


<vector-empty.cpp>=

  1. include <iostream>
  2. include <vector>

using namespace std; int main() { vector<int> v1; vector<int> v2(10); vector<int> v3(10,7); cout << "v1.empty() has value " << v1.empty() << endl; cout << "v2.empty() has value " << v2.empty() << endl; cout << "v3.empty() has value " << v3.empty() << endl; }


Accessing Elements of a Vector

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


vector<int> v; // ... for (int i=0; i<v.size(); i++) cout << v[i?;


(which is very similar to what you might write for a builtin array).

You can also use operator[? to set the values of the elements of a vector.


vector<int> v; // ... for (int i=0; i<v.size(); i++) v[i? = 2*i;


The function front gives access to the first element of the vector.


vector<char> v(10,'a'); // ... char ch = v.front();


You can also change the first element using front.


vector<char> v(10,'a'); // ... v.front() = 'b';


The function back works the same as front but for the last element of the vector.


vector<char> v(10,'z'); // ... char last = v.back(); v.back() = 'a';


Here is a simple example of the use of [?.


<vector-access.cpp>=

  1. include <vector>
  2. include <iostream>

using namespace std; int 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; }


Inserting and Erasing Vector Elements

Along with operator[? as described above there are a number of other ways to change or access the elements in a vector.

  • push_back will add a new element to the end of a vector.

*

  • pop_back will remove the last element of a vector.

*

  • insert will insert one or more new elements, at a designated position, in the vector.

*

  • erase will remove one or more elements from a vector between designated positions.

*

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.


<vector-mod.cpp>=

  1. include <iostream>
  2. include <vector>

using namespace std; int main() { vector<int> v; 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; 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; int a1[5?; for (int i=0; i<5; i++) a1[i? = 100; 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; v.erase(& v[4?,& v[7?); cout << "Vector now contains:" << endl; for (int i=0; i<v.size(); i++) cout << v[i? << ' '; cout << endl; }


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.

  • push_back takes a single argument of the type of the elements held in the vector.

*

  • pop_back takes no arguments. It is a mistake to use pop_back on an empty vector.

*

  • insert has three forms:

    • insert(pos, T& x) which will insert the single element x at position pos in the vector.

    *

    • insert(pos, start, end) which inserts a sequence of elements from some other container at position pos in the vector. The

    *

    • sequence of elements is identified as starting at the start element and continuing to, but not including, the end element.

    *

    • insert(pos, int rep, T& x) inserts rep copies of x at position pos in the vector.

    *

*

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).

  • erase has two forms (pos, start and end have the same types as for the insert function):

    • erase(pos) which will remove the element at position pos in the vector.

    *

    • insert(start,end) which will remove elements starting at position start upto, but not including, the element at position end.

    *

*

Vector Iterators

The simple way to step through the elements of a vector v is as we have done above:


for (int i=0; i<v.size(); i++) { ... v[i? ... }


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.

For a vector containing elements of type T:


vector<T> v;


an iterator is declared as follows:


vector<T>::iterator i;


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 *.

Fatal Error:

lib/CachedMarkup.php (In template 'browse' < 'body' < 'html'):257: Error: Pure virtual

lib/InlineParser.php:336: Warning: Invalid [] syntax ignored: [[In fact vector iterators allow more operations on them - see next

  • section for more information]


Fatal PhpWiki Error

lib/CachedMarkup.php (In template 'browse' < 'body' < 'html'):257: Error: Pure virtual