수안이의 컴퓨터 연구실

  • Mainpage
  • About Me
  • Tags
  • Metapage
  • Notice
  • Location
  • Keywords
  • Guestbook
  • Admin
  • Write an Article
  • Total | 1694007
  • Today | 358
  • Yesterday | 588

Programming/STL2007/07/17 14:09

A beginner's tutorial on STL

By  Mahesh Chand August 04, 2000

Ok, guys, here is one more beginner's tutorial. This time it's STL. Are you new to STL and interested in knowing what STL is? Or how to use STL in your program? I bet this tutorial is for you. If you are an advanced user of the STL then see my references and links at the end of this tutorial.

The Evolution

The Standard Template Library (STL) is not a new library as compared to other libraries. Originally, the development of the STL was started by Alexander Stepanow at HP in 1979. Later, he was joined by David Musser and Meng Lee. In 1994, STL was included into ANSI and ISO C++.

Why the STL?

In one of my projects, I needed a doubly linked-list to store a tree's node values. One of my fellow developer's created this class which has general functions such as addNode, deleteNode, SeachNode, InsertNode and others. It took him more than a week and we still had some memory problems in it.

The STL provides general purpose utility classes which programmers can use in their applications and they don't have to worry about allocating and freeing memory. These classes are array, link, stack and map. The STL provides general algorithms for sort, search, or reverse arrays or links. Besides these two things, the STL also provides some iterators and other options you can apply on these classes.

Features: The STL's generic algorithms work on native C++ data structures such as strings and vectors. STL containers are very close to the efficiency of hand-coded, type-specific containers. Learning of STL is very simple. You need some knowledge of templates and C++.

When to use the STL?

If you need to provide any STL features in your program, you can use them.

Advantages of the STL

  • You don't have to write your classes and algorithms. It saves time.
  • You don't have to worry about allocating and freeing memory. That's a big problem when you create your own linked-list, queue or other classes.
  • Reduces your code size because STL uses templates to develop these classes.
  • You have to override your functions or classes to operate on different types of data while STL lets you apply these classes on different kinds of data.
  • Easy to use and easy to learn.

Templates

The STL classes are template based classes. You should know about templates before starting using the STL in your programs.

A template is a mechanism for generating functions and classes which can apply on different types of data. You can design a single class that operates on different type data. For example, you can create a linked list class which can work on int, long, or double data types. We will see this in the following example.

There are two types of templates: function templates and class templates.

Function Templates

Function templates allow you to write type safe functions and it can reduce size of code and create code flexibility. For example, you have an overloaded function Add() which is defined here:

int Adding a, int b ) { return a + b; } ;
long Add( long a, long b) { return a + b; } ;
double Add( double a, double b ) { return a + b; } ;

Instead, you can write a template function, Add, which will solve this overloading problem.

template <class T>
T Add( T a, T b) { return a + b };

Now you can use this template on different types of data. Such as:

int total = Add<int>(12, 35);
long total = Add<long>(10245, 35234);
double total = Add<double>(12.60, 35.98);

Fairly easy. huh?

Class Templates

Templates allows you to create classes that do not operate on a specific data type. Instead, the data type can be provided by the user at runtime. Here is an example. We have a class Math, which has three functions, Add, Divide, and Multiply.

template <class T>
class Math {
public:
Math(){ };
T Add( T a, T b) { return a + b };
T Divide( T a, T b) { return a + b };
T Multiply( T a, T b) { return a + b };
};

Now you can use this class with different data types. Here is how to use it:

Math<double> dMath; // Instantiating the class for double data type.
double dReturn = dMath.Add ( 12.34, 34.654 );
double dReturn = dMath.Multiply ( 12.34, 34.654 );
Math<int> iMath; // Instantiating the class for integer data type.
int iReturn = dMath.Add ( 12, 34 );
int iReturn = dMath.Multiply ( 12, 34 );

Does it make sense? Ok, that's enough about templates.

Basic elements of the STL

Here is a list of elements of the STL. The first three of them are fundamental items.

Item Description
Container An object that holds other objects
Algorithm A function that acts on containers
Iterator A pointer-like object
Allocator This item manages memory allocation in a container
Adaptor Transforms one object into another
Predicate A function that returns a boolean value, true or false.
Function Object A class that defines operator().

Containers are the basic elements of the STL. A container is the component that actually stores data. For example, the deque container class creates a doubly linked-list and the list class creates a linked-list.

Algorithms are the second most useful element of the STL. Algorithms act on the containers. They are used to perform operations on the containers such as sorting, searching and others.

Iterators work as their name says :). They  provide iterations for the STL containers. Iterations mean looping. For example, if you want to search a container item from beginning to the end, you would have to use iterators for this loop.

Allocators manage memory allocations for the containers.

An adaptor is used to convert from one object to another. They are a kind of conversion utilities. For example, you can convert a dque container to queue using a queue adaptor.

Function Objects are utility functions that are used on the containers. Some of them are less(), greater(), divides(), plus(), minus() etc. We will see how to use them in our sample programs.

The Containers

Containers are the base elements of the STL. Containers holds actual data. I should say that containers are data structures that store, and manage a set of items. Containers have constructors and destructors to provide allocation and deallocation for stored items. These items can be a basic data type such as int, char, string etc. All containers are implemented using templates. The good thing about containers is all containers have the same specification.

Sequence A sequence is a linear list which stores all of its elements in linear order. For example an array is a sequence.

char ch[10] is an array of char types (10 elements) which are ordered in a linear fashion.

Those were two types of containers and the third type is container adaptors:

Type Container classes Description
Sequence vector, list, deque Dynamic arrays, support insertion or deletion in the beginning or at the end. They don't support insertion or deletion at a specific position.
Associative map, multimap, set, multiset This type of container is a variable-sized Container that supports efficient retrieval of elements based on keys. They store data in the form of a key and value. A key has corresponding value or values.
Container adaptors stack, queue, priority_queue They are restricted containers and don't support all the functionality provided by containers. We will see this in out definitions later in this tutorial.

Here is a list of the STL container classes and their descriptions.

Container Header file
vector <vector>
deque <deque>
list <list>
set <set>
multiset <set>
map <map>
multimap <map>
queue <queue>
priority_queue <queue>
stack <stack>


Let's see these containers in detail now.

The Vector container

Vector container is the simplest container. It supports random access. It provides insertion, and deletion of elements at the end. It is a dynamic array which varies according to need. It supports automatic memory management. For example:

vector<int> vList; // Initializes a vector list of integers
// Fill values in vList using push_back
for ( int i=1; i<20; i++ ) vList.push_back(i);

The deque container

This container is the same as vector container except that the deque container is a queue with both ends. That means elements can be added or deleted from both front and back ends. Elements can also be inserted at any specific position. For example:

deque<int> d1;
d1.push_front(2);
d1.push_back(4);

The list container

A list is a doubly linked list. It supports both forward and backward traversal, and (amortized) constant time insertion and removal of elements at the beginning or the end, or in the middle. Another list container is slist which is a singly linked list. A list container is really useful when elements will be frequently added or removed from the middle of the container and random access to elements is not required.

The map and multimap containers

The map and multimap containers store data in the form of a pair. Each pair has a key and corresponding value(s). For example, pair stdRec = (name<string>, marks<int>). A map can store data of type stdRec which has two elements, a key, and its value. The basic data type of the key might differ from the values. In our example, key name is a string type while the value is int type.

Map containers allow only unique keys. A key can have some value but there won't be any duplicate key. A key may be a name. So basically map is a list of (key,value) pairs. Value can be accessed by using key. For example:

map<string, int> data;
for(int i=0; i<10; i++)
data.insert(pair<string><char>('mcb'+i, 100+i );

Multimap containers are similar to map except they store duplicate keys. That means one key can have more than one value.

The set and multiset containers

Set containers are similar to map containers except that the key part is not separated from the value part. Sets store data in a form where key is a part of value.

Set class supports a set in which unique keys are stored. While multiset lets you have duplicate keys.

set<string> sdata;
sdata.insert("mahesh");
sdata.insert("Owen");
sdata.insert("lara");
set<string>::iterator p = sdata.begin();
do
{
cout<< *p <<" ";
p++ ;
}while (p!= sdata.end() );

The queue container adaptor

The queue is a FIFO queue which has certain restrictions in comparison to other containers. Elements are inserted into a queue from the tail end and removed from the head. Its like a queue on a gas station. The first vehicle fills gas first and the next vehicle comes after the last vehicle. Push and pop are two major operation of the queue.

queue<string> sdata;
sdata.push("mahesh");
sdata.push("Owen");
sdata.push("lara");

while ( !sdata.end() )
{
cout<< sdata.front() <<" ";
sdata.pop();
}

The stack container adaptor

The stack is a LIFO queue. Operations are similar to queue except elements are inserted from the top of the stack and removed from the top of the stack too. For example, a stack of plates in the kitchen. Push and pop are two major operation of the stack.

stack<string> sdata;
sdata.push("mahesh");
sdata.push("Owen");
sdata.push("lara");

while ( !sdata.empty() )
{
cout<< sdata.top() <<" ";
sdata.pop();
}

The Algorithms

Algorithms are used on the data of containers.

Some basic algorithms are sort, search, count, reverse, or merge. Using these algorithms on containers is pretty easy. For example, if you have a vector container with some data in it, here is how to use the count algorithm to count its elements:

vector<int> vdata;
//add some data 
int i = count( vdata.begin(), vdata.end(), 3 );

Here is reverse algorithm:

vector<int> vdata;
// add some data
reverse( vdata.begin(), vdata.end() );

Lets see one more example of sorting the data.

vector<int> vdata;
vdata.push_back(5);
vdata.push_back(3);                                                                  vdata.push_back(8);
s
ort(vdata);

STL has over 60 algorithms listed here with their description.

Algorithm Description
adjacent_find Searches for adjacent matching elements within a sequence and returns and iterator to the first match
binary_search Performs a binary search on an ordered sequence
copy Copies a sequence.
copy_backward Same as copy except that it moves the elements from the end of the sequence first
count Returns the number of elements in the sequence.
count_if Returns the number of elements in the sequence that satisfy some predicate.
equal Checks if two ranges are same
equal_range Returns a range in which an element can be inserted into a sequence without disrupting the ordering of the sequence.
fill and fill_n Fills a range with a specified value
find Searches and returns the iterator  to the first occurence
find_end Last iterator
find_first_of Finds the first element
find_if Searches with a predicate
for_each Applies a function to a range of elements
generate and generate_n Assigns elements in a range of the values returned by a generator function.
includes Determines if one sequence includes all elements of other sequence.
implace_merge Merges a range with another range
iter_swap Exchange the values pointed to by its iterator arguments
lexicographical _compare Compares two sequences alphabetically
lower_bound Find the first point in the sequence that is less than a specified value.
make_heap Constructs a heap from a sequence.
max Returns the maximum of two values.
min Returns minimum of two values.
min_element Returns the iterator to the min element within a range.
mismatch Finds the first mismatch between the elements in two sequences.
next_permutation Constructs next permutation of a sequence.
nth_element Arranges all elements in an order so all element less than nth element come before it and greater than come after it.
partial_sort Sorts a range.
partial_sort_copy Sorts and copies elements.
partition, stable_partition Arranges elements so all elements return true for a predicate coming before it and false coming after it.
pop_heap Exchanges first and last-1 elements
prev_permutation Constructs previous permutation
push_heap Pushes elements onto the end of the heap.
random_shuffle Randomize a sequence.
remove, remove-if, remove_copy, remove_fopy_if Removes elements
reverse and reverse_copy Reverses the order of a range
replace, replace_if, replace_copy, replace_copy_if Replaces elements within a range.
rotate, rotate_copy Left-rotate
search, search_in searches a subsequence within a sequence
set_difference Provides difference between two ordered sets.
set_intersection Provides intersection output between two sets.
set_symmetric_ difference Provides symmetric output between two sets.
set_union Provides union of two sets.
sort, stable_sort Sorts a range.
sort_heap Sorts a heap.
swap, swap_ranges Exchanges two values, ranges.
transform Applies a function to a range of elements and stores outcome in a new sequence.
unique, unique_copy Eliminates duplicate elements.
upper_bound Finds the last point in a sequence.
merge Merges two sequences.

Iterators

Containers do not provide access to their elements. They use iterators to traverse the elements within a container. In other words, the iterators provides a way to cycle through the contents of containers. Each container defines one or more iterator types that we can declare iterators for that container. There are five types of iterators. Iterators are very similar to smart pointers and have increment and dereferencing operations.

Type Description
Random Access Stores and retrieves elements randomly.
Bidirectional Stores and retrieves elements forward and backward both directions.
Forward Stores and retrieves forward only.
Input Forward retrieve only.
Output Forward, store only.

As we have seen in our previous examples, we can use iterators like in this sample : set<string> sdata;
sdata.insert("mahesh");
sdata.insert("Owen");
sdata.insert("lara");
set<string>::iterator p = sdata.begin();
do
{
cout<< *p <<" ";
p++ ;
}while (p!= sdata.end() ) ;

Function Objects

A function object is an object that can be called as a function. The header for functional objects is <functional>. There are three types of function objects:

Name Description
Generator Generator is a function object which doesn't take any parameters. Such as Do();
Binary A binary function object is a function object which takes two arguments. Such as Do( int a, char b). Some of them are plus, minus, divides, modulus, equal_to, not_equal_to, greater_equal, greater, less, less_equal, local_and, logical_or
Unary A unary function object takes a single argument as a parameter. Such as Do(false); logical_notnegate

Function Adaptors

The same class header <functional> defines function adaptors. Function Adaptors are template classes that provide an existing class with a new interface. They can be applies on container or iterators.

Container Adaptors

What if you need to create a new container from an existing one? That means you need to extend the functionality of an existing one and add some more to new one. You can do that by mapping the interface of an existing container to that of the new container.

The STL provides three container adaptors: stack<Container>, queue<Container>, and deque<Container>. The following program demonstrates the use of a stack that has been implemented as a vector:

#include <vector.h>
#include <stack.h>
void
main()  {
  stack <vector<int> > st;
  for (int i=0; i < 10; i++)
     st.push (i);
  while ( !st.empty() )
  {
     cout << st.top() << " ";
     st.pop();
  }
  cout << endl;
}

Iterator Adaptors

Adaptors can also be used to extend the functionality of an existing iterator. The reverse, insert, and row storage iterators are example of iterator adaptors in the STL.

Allocator

Allocators are responsible of memory management in the STL. Each container has one its allocator. Allocators allocate and deallocate memory automatically for a container. But you can even create your own custom allocators.

The default allocator is Allocator. It is defined in the <memory> header file. This table shows allocator's functions and their description:

Function Description
pointer address(reference ob) const; const_pointer address ( const_reference ob) const; Returns the address of object ob.
pointer allocate(size_tpe num, typename allocator<void>::const_pointer h=0); Returns a pointer to allocated memory
void construct(pointer ptr, const_reference val); Constructs an object
void deallocate(pointer ptr, sise_type num); Deallocates num object
void destroy(pointer ptr) Destroys ptr object.
size_type max_size() const throw(); Returns the maximum number of objects that can be allocated.

Example:

vector<double>::allocator_type d_a;
cout<< d_a.max_size();

REFERENCES AND LINKS: If you are interested in more details of the STL, here are more links of STL documentation with sample examples.

  • STL documentation and detailed description with sample examples. Everything you need about STL. http://www.sgi.com/Technology/STL
  • STL examples for every algorithm http://www.sgi.com/technology/stl/table ··· nts.html
  • STL Books and other good links  http://www.sgi.com/Technology/STL/other_resources.html
  • Download the STL and its versions http://www.sgi.com/Technology/STL
  • The Standard Template Library by Alexander Stepanov and Meng Lee (ANSI/ISO document)
  • Algorithm-oriented Generic Libraries by David R. Musser and Alexander A. Stepanov
"STL" 카테고리의 다른 글
  • A beginner's tutorial on STL (0)2007/07/17
  • 표준 템플릿 라이브러리(STL, Standard Template L... (0)2007/05/17
  • 함수대신 function object를 대입하자 (0)2007/03/23
  • 정렬과 탐색 루틴이 필요하신 분 (0)2007/03/23
2007/07/17 14:09 2007/07/17 14:09
Posted by webdizen
Tags C++Keyword C++, STL
No Trackback No Comment

Trackback URL : http://www.webdizen.net/blog/trackback/3076

Leave your greetings.

[로그인][오픈아이디란?]

«Prev  1 ... 184 185 186 187 188 189 190 191 192 ... 3009  Next»

RSS HanRSS
Blog Image
webdizen
이곳은 컴퓨터에 대해 연구하고, 공유하고, 소통하기 위한 연구실입니다. 개인적으로는 OLAP, Data Mining, Semantic Web, Data Modeling에 대해서 연구하고 있습니다.

Categories

전체 (3009)
Webdizen (141)
Life (6)
Diary (16)
Blog (9)
IDEA (2)
Travel (10)
Book (16)
Photo (7)
Movie (8)
Music (14)
Leisure Sports (10)
Funny (6)
Hardware (121)
Software (120)
Windows (5)
Unix & Linux (120)
Installation (5)
Kernel (10)
System (34)
Develop (22)
X-Window (0)
Applicaton (31)
Security (4)
Framework (2)
Hadoop (2)
Programming (804)
Algorithm & Data Structure (1)
Assembly (38)
UNIX/Linux C (95)
C++ (128)
STL (4)
Java (38)
Win32 API (92)
ATL/COM (44)
MFC (151)
.NET (26)
WCF/WPF (4)
C# (28)
Network Programming (17)
Database Programming (12)
OpenGL / DirectX (13)
Multimedia Programming (0)
Game Programming (21)
Parallel Distributed Progra... (0)
Reverse Engineering (0)
Debugging (9)
Python (1)
Ruby (1)
Ruby on Rails (1)
QT (4)
GTK (0)
JSP (0)
PHP (6)
ASP.NET (6)
ASP (2)
Development (28)
Useful Library (2)
Data Modeling (0)
Database (105)
Oracle (4)
MSSQL (41)
MySQL (2)
Data Warehouse (2)
Data Mining (4)
Network (66)
Web (79)
DHTML (4)
XHTML (1)
Javascript (1)
CSS (1)
AJAX (9)
XML (11)
Flex (1)
Silverlight (3)
Security (91)
DoS (1)
Kernel (10)
Scanning (3)
Sniffing (0)
Spoofing (4)
Overflow (28)
Web (11)
Shell (10)
Format String (14)
Window (2)
Embedded (70)
Multimedia (27)
Mobile (14)
Graphic (24)
Management (633)
Knowledge (581)
Hadoop (0)

Notice

  • 메타 블로그 사이트에 등록
  • 새해 맞이 블로그의 변화
  • 블로그 명칭 변경
  • 도메인(www.webdizen.net) 구...
  • TEXTCUBE 1.6.1로 업그레이드...

Tags

  • 시스템 제어
  • ER Conference
  • w3m
  • 버전 관리
  • dialog
  • 다이얼로그
  • 율곡관
  • iostream.h
  • 박물관
  • mapping
  • 지식탐사
  • 로그
  • 개발
  • 동의어
  • 시그널
  • 블로그
  • TED
  • RADIUS
  • Zend Framework
  • Hyper-V

Recent Articles

  • 트위터(Twitter)의 시작!.
  • 청년 리더의 조건.
  • 애플의 타블렛 PC - 아이패드....
  • 미래의 인터페이스 - 육감 기....
  • 기초발성법 동영상 강좌.

Recent Comments

  • 학교 과제물중 쓰레드에 대하....
    장진혁 03/17
  • 관리자만 볼 수 있는 댓글입....
    비밀방문자 03/12
  • 상대방의 이야기를 열심히 경....
    DoNuts 03/03
  • Lots of students know techn....
    Bobbi35Shannon 02/25
  • 좋은글 잘 보고 갑니다..
    Und_hacker 01/08

Recent Trackbacks

  • printf,scanf를 이용한 형식....
    yundream의 프로그래밍 이야기 03/10
  • 파일 열기/저장하기 CFileDialog.
    은마군의 나태블록 2009
  • World IT Show 2008.
    상우 :: Oranzie's BLOG 2008
  • cvs서버 설치하기.
    3인3색 2008
  • 속속 공개되는 Google Chart....
    PHP와 Web 2.0 2007

Archive

  • 2010/02 (1)
  • 2010/01 (6)
  • 2009/12 (5)
  • 2009/09 (3)
  • 2009/08 (1)

Calendar

«   2010/03   »
일 월 화 수 목 금 토
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      

Bookmarks

    • Administration
      • IIS.NET
      • NTFAQ
      • OS의 모든 것
      • 리눅스포털
    • Database
      • SQL Server Central
      • SQL Team
    • Development
      • .NET Heaven
      • ASP Alliance
      • ASP.NET 2.0
      • Bullog.net
      • C# Corner
      • C++ (C PlusPlus.com)
      • C++ Reference
      • CodeGuru
      • CodePlex
      • DebugLab
      • Dev Articles
      • Devpia
      • DotNet Junkies
      • DotNet Zone
      • Driver Online
      • GOSU.NET
      • HOONS 닷넷
      • Joinc 팀블로그
      • KOSR
      • MSDN Home Page
      • OSR Online
      • Sky.ph - 개발자 커뮤니...
      • TAEYO.NET
      • The Code Project
      • WindowsClient.net
      • 김상욱의 개발자 Side
      • 조인시 위키
    • Human Networks
      • belief21c's e-space
      • I think I can
      • Invisible Rover's Blog :D
      • Rodman®
      • ■ Feel So Good~! ■
      • 까만 나비
      • 나를 가꾸는 시간.
      • 나만의 즐거움~~!
      • 단녕
      • 상우 :: Oranzie's BLOG
    • Information Technology
      • Microsoft TechNet
      • 지디넷코리아 - 글로벌...
    • Security
      • FoundStone
      • milw0rm
      • NewOrder
      • OpenRCE
      • Phrack.org
      • Reverse Engineering b1...
      • Reverse Engineering Team
      • RootKit
      • SecurityFocus
      • SecurityXploded by Nag...
      • Wow Hacker
      • Zone-H
Textcube
Louice Studio Inc.
Powered by Textcube. Original designed by Tistory.