Click here to Skip to main content
15,891,431 members
Articles / Programming Languages / C++
Article

Using STL

Rate me:
Please Sign up or sign in to vote.
4.35/5 (20 votes)
29 Dec 1999 178.2K   44   22
A brief introduction on using the Standard Template Library

Introduction

My C++ programming background comes from DOS Borland C++. In their latest DOS version 3.1, they included a template library for collections. It was a great piece of work. When I started to use Visual C++ v2.2, I even tried to use Borland's collection template library within Visual C++ but with no success. The only other solution was to switch to Microsoft's collections that are part of the MFC. However, this was always a problem for the following reasons:

  • It is not easy to switch from one container type to another once the application is written (from list to array for example).
  • Iterators are different for different type of containers.
  • If one is writting a DLL, service or a console application and needs containers, the solution is to either dynamically or statically link MFC which makes the project dependent on MFC.

Recently, I started using STL and it is great. The beginning was a bit difficult but once I grasped the idea, it was easy. This article contains some first hand experiences with STL and is intended for programmers that want to use STL fast and without going into greater details.

Rule 1:

You can create STL containers that store either objects or pointer to objects.

class TMyClass;
typedef list<TMyClass> TMyClassList;     // Stores objects into the list container
typedef list<TMyClass*> TMyClassPtrList; // Stores pointers to object into the list container

Usually, list container that stores the object is used. However, if the object is using a machine resource (handle to file, named pipe, socket or similar), then it is more appropriate to use lists that stores pointers to objects.

If the container stores objects, then it is automatically cleaned up during container destruction. However, if it stores pointers to objects, programmer is responsible to delete all pointers.

Rule 2:

Each class (whose instance will go into the container) must implement at least the copy constructor (it is good to implement also the assignment operator.
class TMyClass {
    private:
        ...
    public:
        TMyClass(..);

        // Copy constructor
        TMyClass(const TMyClass& obj)  { *this = obj; }

        // Assignment operator
        TMyClass& operator=(const TMyClass& obj);    
        ...
};

This is necessary since the STL will create a local copy of the object when you insert an object instance into the container. If you do not write a correct code for the copy constructor, object within a list will have some data members uninitialized.

Rule 3:

Inserting an object into the container is done in the following way:

TMyClass object;
TMyClassList myList;
TMyClassList::iterator it;

it = myList.insert(myList.end(), object);
TMyClass *pObject = &(*it);

Previous example shows how to insert an object into the container and obtain a pointer to the object within container. This is necessary since the container will create a new copy of the "object" instance and the original "object" instance is not used any more. In case you are storing pointers to a list, this is not necessary since original pointer is stored into the container.

Rule 4:

Iterating through container is done in the following way:

TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++) {
    pObject = &(*it);
    // Use pObject 
}

However, if you are storing pointers into the container, then the previous code fragment has to be modified to the following:

TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++) {
    pObject = *it;
    // Use pObject 
}

Rule 5:

Removing items from the container is done in the following way:

TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++) {
    pObject = &(*it);
    if (pObject satisfies some delete criteria) then
        myList.erase(it);
        // If pointers are stored in a list then add
        delete pObject;
}

Additional line to delete the pointer to the object is needed since the container will not delete a stored pointer so it has to be manually deleted.

Conclusion

The only thing that is missing from STL is a function similar to CString::Format() function.

I hope that this article will give you enough information to start using STL. You will be surprised how easy it is.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer SCA d.o.o.
Serbia Serbia
I am a cofounder of SCA Software, company that specializes in software for process control, visualization and communication. Programming for the last 10 years in C++, Delphi. Visual C++ for the last 6 years. Degree in Electronics Engineering and Telecommunications.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Member 1131211128-Mar-15 4:29
Member 1131211128-Mar-15 4:29 
GeneralMy vote of 3 Pin
BillW3324-Sep-10 4:13
professionalBillW3324-Sep-10 4:13 
GeneralChecking valid pointers Pin
LordMarv12-Apr-05 4:50
LordMarv12-Apr-05 4:50 
GeneralVector Pin
arvind_tyche10-May-04 3:50
arvind_tyche10-May-04 3:50 
GeneralRe: Vector Pin
toxcct10-May-04 4:28
toxcct10-May-04 4:28 
GeneralEffective STL Pin
Jonathan de Halleux8-Dec-03 21:35
Jonathan de Halleux8-Dec-03 21:35 
GeneralRe: Effective STL Pin
peterchen13-Jul-04 3:26
peterchen13-Jul-04 3:26 
GeneralRule 2: Copy constructor not required Pin
Andrew Phillips8-Dec-03 21:13
Andrew Phillips8-Dec-03 21:13 
GeneralMany many ambiguous symbol errors Pin
JWood21-Aug-03 5:11
JWood21-Aug-03 5:11 
GeneralError: No copy contructor available Pin
minty11-Feb-03 15:15
minty11-Feb-03 15:15 
GeneralRe: Error: No copy contructor available Pin
Christian Graus11-Feb-03 16:01
protectorChristian Graus11-Feb-03 16:01 
GeneralRe: Error: No copy contructor available Pin
minty12-Feb-03 10:57
minty12-Feb-03 10:57 
GeneralCString::Format() Pin
Moak19-Aug-02 21:27
Moak19-Aug-02 21:27 
GeneralRe: CString::Format() Pin
Anonymous6-Aug-03 23:54
Anonymous6-Aug-03 23:54 
QuestionAre string templates threadsafe? Pin
Nidhi Narang7-Dec-01 7:05
Nidhi Narang7-Dec-01 7:05 
AnswerRe: Are string templates threadsafe? Pin
Bryan Labutta7-Feb-02 8:39
Bryan Labutta7-Feb-02 8:39 
Actually, the string templates are not threadsafe. I learned this the hard way while a project I was working on was trying to go live. The project was multi-threaded, but was only on a single-processor machine. During all of the system tests, the application ran flawlessly. On the day it went into production, though, it crashed within a half hour.

After a couple weeks, I found out that the strings are maintained through reference counts. The way the application was set up there were internal custom STL queues set up to pass messages between threads. On a single processor box this worked fine, but when it was moved to a dual-processor box, the concurrency of the threads caused problems with messages placed in the queues.

Our solution to this was to place the messages into the queues using character arrays (char*) so that we did not have to worry about the thread safety of the STL strings. I cannot say for sure that this is only a multi-processor problem, but all of the references I could find and all of my experiences through testing point me in believing that option.


Bryan Labutta
GeneralRe: Are string templates threadsafe? Pin
26-Mar-02 16:03
suss26-Mar-02 16:03 
GeneralRule 5 removing items Pin
Michael S. Scherotter18-Mar-00 4:39
Michael S. Scherotter18-Mar-00 4:39 
GeneralThanks! Pin
clintsinger21-Nov-01 19:52
clintsinger21-Nov-01 19:52 
GeneralRe: Thanks! Pin
Michael S. Scherotter25-Nov-01 12:16
Michael S. Scherotter25-Nov-01 12:16 
GeneralRe: Rule 5 removing items Pin
Moak19-Aug-02 21:34
Moak19-Aug-02 21:34 
GeneralMissing Format - use std::ostringstream Pin
Ken Nicolson31-Jan-00 13:00
sussKen Nicolson31-Jan-00 13:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.