Click here to Skip to main content
15,881,709 members
Articles / Programming Languages / C++

Practical Guide to STL

Rate me:
Please Sign up or sign in to vote.
4.41/5 (65 votes)
12 Apr 200412 min read 492.9K   2.2K   117  
An article on practical learning of STL in the MS development environment.
// Program: Vector Demo
// Purpose: To demonstrate STL vectors

// #include "stdafx.h" - include if you use pre compiled headers
#include <vector>	// STL vector header. There is no ".h"
#include <iostream>	// for cout
using namespace std;	// Ensure that the namespace is set to std

char* sHW = "Hello World";	
// This is - as we all know - a character array, terminated with a null character

int main(int argc, char* argv[])
{
	vector <char> vec;	// A vector (STL array) of characters

	// Define an iterator for a vector of characters - this is always 
	// scoped to within the template
	vector <char>::iterator vi;

	// Initialize the character vector, loop through the string, 
	// placing the data in the vector character by character until 
	// the terminating NULL is reached
	char* cptr = sHW;	// Start a pointer on the Hello World string
	while (*cptr != '\0')
	{	vec.push_back(*cptr);	cptr++;	}
	// push_back places the data on the back of the vector (otherwise known as the end of the vector)

	// Print each character now stored in the STL array to the console
	for (vi=vec.begin(); vi!=vec.end(); vi++)	
	// This is your standard STL for loop - usually "!=" is used in stead of "<"
	// because "<" is not defined for some containers. begin() and end() retrieve iterators 
	// (pointers) to the beginning of the vector and to the end of vector
	{	cout << *vi;	}	// Use the indirection operator (*) to extract the data from the iterator
	cout << endl;	// No more "\n"

	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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
Canada Canada
I shuffle tiny static charges on intricate wafers of silicon all day.

Comments and Discussions