수안이의 컴퓨터 연구실

  • Mainpage
  • About Me
  • Tags
  • Metapage
  • Notice
  • Location
  • Keywords
  • Guestbook
  • Admin
  • Write an Article
  • Total | 1694414
  • Today | 159
  • Yesterday | 606

2 Articles, Search for 'STL'

  1. 2007/07/17 A beginner's tutorial on STL
  2. 2007/05/17 표준 템플릿 라이브러리(STL, Standard Template Library)를 왜 사용해야 하는가?
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.

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

Programming/STL2007/05/17 17:26

표준 템플릿 라이브러리(STL, Standard Template Library)를 왜 사용해야 하는가?

저자: 김승태 / 유진로보틱스 주임연구원

C++ 언어는 클래스, 멤버함수, 상속, 템플릿, 오버로딩 등의 언어적인 기술 외에 이들을 기반으로 필요하리라 예상되는 기능을 미리 만들어 둔 클래스, 함수 등의 집합체인 라이브러리를 제공한다. 그리고 이를 표준 라이브러리(Standard Library)라고 부른다. 이 표준 라이브러리에는 C 언어에서 널리 사용되던 도구가 들어있어 이를 이용해 C++에서도 입출력, 문자열 처리, 메모리 관리 등을 손쉽게 할 수 있다.

1980년 뱐 스트라우스트럽(Bjarne Stroustup)에 의해 탄생한 C++ 언어는 몇 번의 역사적인 큰 사건을 겪고 오늘날의 모습을 갖추게 되었다. 그 중 하나가 바로 1994년에 있었던 표준 템플릿 라이브러리의 도입이다. 이 변화는 알렉산더 스테파노프(Alexander Stepanov)가 주도하였다. 알렉스는 표준 라이브러리에 템플릿(Template)을 기반으로 한 클래스와 함수를 추가로 도입할 것을 제안하였고, 이 클래스와 함수를 “컨테이너(Container)”와 “알고리즘(Algorithm)”라 불렀다. 추가 요청을 한 클래스가 스택(Stack), 큐(Queue) 등의 데이터 구조이고, 함수는 대다수가 이 데이터 구조와 함께 연동해 작업을 수행하기 때문에 이 이름을 선택한 것이다.

템플릿 기반의 클래스와 함수는 미국 표준 위원회(ANSI, America National Standard Institute)에서 제정하는 C++ 표준에서 1995년에 처음으로 표준 템플릿 라이브러리(STL, Standard Template Library)라는 이름으로 만장일치로 도입되었고, 이후 국제 표준화 기구가 제정하는 C++ 언어에서 표준 라이브러리와 완전히 흡수되면서 표준 라이브러리로 통합되었다. 그리고 표준은 기술 보고서 TR1(Technical Report)에 있는 내용을 중심으로 표준 라이브러리를 계속 확장하고 있다.

표준 템플릿 라이브러리가 표준 라이브러리로 통합되어 이제 표준 템플릿 라이브러리라는 명칭을 사용하는 것은 어쩌면 역사적인 사건을 가리킬 때나 사용해야 올바른 것일지도 모른다. 그러나 현재도 표준 템플릿 라이브러리를 처음 구현했던 HP의 STL을 계승한 SGI에서도 여전히 표준 템플릿 라이브러리라는 용어를 사용하고 있으며, 많은 국제 C++ 언어 전문가들 역시 표준 템플릿 라이브러리라는 용어를 사용하고 있다. 비록 C++ 언어의 국제 표준(IS, International Standard)인 14882에서는 공식적인 언급이 전혀 없지만.

표준 템플릿 라이브러리는 컨테이너(Container), 알고리즘(Algorithm), 이터레이터(Iterator), 그리고 함수 개체(Functor, Function Object)로 크게 구성되어 있다. 이들에 대해 각각 살펴보자.

• 컨테이너
같은 타입의 원소를 관리하는 선형적인 데이터 구조를 지원하는 클래스로, 일종의 지능화된 동적 배열이다. 원소를 추가하거나 삭제할 수 있고, 크기 변경에 따라 내부에서 메모리를 관리해서 개발자가 메모리를 직접 관리하는 부담을 줄여준다. 컨테이너에는 크게 시퀀스 컨테이너 계열(Sequence Container)과 연관 컨테이너 계열(Associated Container)이 있는데, 시퀀스 컨테이너 계열은 원소를 스택, 큐, 리스트 등의 데이터 구조에 담아 관리하고, 연관 컨테이너 계열은 균등 트리(Balanced Tree)에 담아 원소를 관리한다. 이 외에도 현재 표준화가 진행 중인 C++03(ISO/IEC 14882:2003의 약칭)의 차기 버전인 C++0x에서는 해시 기반의 연관컨테이너(Hashed Associated Containers)가 새롭게 추가될 것으로 기대된다.

• 알고리즘
이터레이터를 통해 시퀀스 컨테이너에 일정한 구간에 정하고, 이에 대해 복사, 전환, 병합, 정렬 등의 연산을 지원한다. 이들은 크게 입력된 이터레이터가 가리키는 곳에 변화를 주는 변형 알고리즘과 변화를 주지 않는 불변형 알고리즘, 정렬에 관련된 정렬 알고리즘으로 분류된다. 변형 알고리즘에는 구간 내 원소의 순서를 뒤 섞는 random_shuffle, 조건에 맞는 원소를 교체하는 replace, 구간 내 원소를 모두 같은 값으로 바꾸는 fill, 구간 내 원소를 주어진 함수가 반환하는 값으로 바꾸는 generate, 조건에 맞는 원소를 제거하는 remove, 동일한 값을 가지는 원소를 제거하는 unique 등이 있다. 불변형 알고리즘에는 주어진 구간에 있는 모든 원소에 접근하여 for 문의 역할을 할 수 있도록하는 for_each, 두 시퀀스를 비교하여 다른 곳이 있는지를 찾는 mismatch, 두 시퀀스가 같은 값을 가진 원소들인지를 확인하는 equal 등이 있다. 정렬 알고리즘에는 구간 내 원소를 정렬하는 sort와 안정적인 조건을 추가로 하는 stable_sort가 대표적이고, 상위 n개만 정렬하는 nth_element, 주어진 값을 갖는 최초 원소를 찾는 lower_bound, 마지막 원소 바로 다음을 찾는 upper_bound, 주어진 값을 갖는 구간을 가리키는 이터레이터를 반환하는 equal_range, 두 시퀀스를 합치는 merge, 집합 연산을 제공하는 set_union, set_intersection, set_diiference 등이 있다.

• 이터레이터
원소를 관리하는 방법을 제공하는 컨테이너의 위상에 걸맞게 포인터의 개념을 한층 일반화시킨 지능화된 포인터다. 이터레이터는 내부적으로 실제 포인터를 관리하는 클래스며, 포인터를 이용해 다양한 형태의 데이터 구조를 일관된 방법으로 원소에 접근할 수 있는 방법을 제공한다. 이터레이터에서는 포인터를 사용하는 데 쓰는 연산자인 *, ->, ++, -- 등을 이터레이터에 맞게 오버로딩하였기 때문에 일반의 포인터와 같은 방식으로 사용할 수 있다. 즉, 사용 목적에 따라 입력용 InputIterator, 출력용 OutputIterator, 입출력용 ForwardIterator, 양방향 BidirectionalIterator, 임의 접근용 RandomAccessIterator 등으로 기능을 세분화하여 그 이름으로부터 손쉽게 이터레이터의 역할을 이해할 수 있도록 하고, 기능을 제한함으로써 잠재적으로 날 포인터(Raw Pointer)를 무분별하게 사용하기 때문에 발생할 수 있는 에러의 가능성을 원척적으로 봉쇄하는 역할을 한다.

• 함수 개체
함수개체는 연산자 ( )를 오버로딩한 클래스로, 컨테이너, 알고리즘 등에서 비교를 위해 연산자 <를 대체하는 등의 지능화된 함수 역할을 한다. 표준 라이브러리에서는 많이 쓰는 기능을 중심으로 함수 개체를 미리 정의하여 제공하고 있다. 이들은 크게 산술 계산용으로 사용되는 plus, minus, multiplies, divides, modulus, negate, 비교 연산에 사용되는 equal_to, not_equal_to, greater, less, greater_equal, less_equal, 논리 연산에 사용되는 logical_end, logical_or, logical_not으로 구분된다. 그러나 함수 개체 자체가 함수형 프로그래밍의 기본적인 도구가 되지만, 표준 템플릿 라이브러리가 완전한 함수형 패러다임을 하는 것은 아니다.

• C++ STL 실전 프로그래밍
표준 템플릿 라이브러리에는 기존의 라이브러리와 달리 몇 가지 큰 장점이 있다. 스택, 리스트, 큐, 균등 트리 등의 데이터 구조에 대한 직관적인 인터페이스를 제공해 사용자가 손쉽게 사용할 수 있다. 또한 정렬, 이진 탐색, 찾기, 병합(Merge), 최대 원소 관리, 상위 n개의 원소 검색 등의 고급 알고리즘도 제공한다. 이런 고급 연산 기능은 기존 라이브러리에서 제공하는 저수준 기능과는 크게 달라진 점이다. 그리고 이 기능은 예외 처리를 기반으로 제공된다. 예를 들어 컨테이너에 저장되어 있는 어떤 원소에 대해 접근하기 위해 사용되는 함수 at은 지정된 매개변수가 접근할 수 있는 범위를 넘어설 경우 예외 out_out_range를 던진다. 이와 같이 많은 에러가 발생하는 상황에 대해 예외를 정의해 놓아 프로그램이 언제나 제어가 가능한 안전한 상태에 놓일 수 있도록 해 주고 있다. 포인터를 이용한 배열형 메모리의 관리에서 매번 직접 인자를 검사해야 하는 것과는 큰 차이가 있다.

표준 템플릿 라이브러리의 가장 큰 매력은 더 이상 포인터를 관리하지 않아도 된다는 데 있다. 고급 컨테이너와 알고리즘, 그리고 이터레이터가 제공하는 프로그래밍 구조는 포인터가 필요한 대부분의 경우를 대체할 수 있도록 해 주고, 더불어 높은 수준의 에러 처리 구조와 지능적인 연산에 의해 포인터를 직접 사용할 때보다 훨씬 더 안전하고, 효율적으로 데이터를 관리할 수 있도록 도와준다.

두 번째로 표준 템플릿 라이브러리는 제네릭 프로그래밍(Generic Programming)을 기반으로 이루어져 있다. 즉, 템플릿을 기반으로 제공되는 클래스와 함수들은 이들 내부에서 사용하고 있는 각 타입들을 많은 경우 템플릿 매개변수화하여 제공하고 있고, 이에 따라 실행 시간에 비용을 지불하지 않는 높은 효율성을 지닌 프로그램의 일반화가 가능하도록 해 준다.

또한, 표준 템플릿 라이브러리는 표준의 일부이기 때문에 g++, 비주얼 C++ 등의 특정한 번역 환경을 가정하지 않아 이를 기반으로 작성된 프로그램이 어느 곳에서나 동일하게 번역되고, 실행되는 것이 보장된다. 즉 작성된 프로그램의 이동성(Portability)이 최대한 보장되는 것이다.

이러한 매력에도 불구하고 많은 C++ 언어 사용자들이 표준 템플릿 라이브러리의 사용을 꺼려하고 있다. 표준 템플릿 라이브러리라고 하면 어려운 전문가의 도구, 혹은 뭔가(?) 특별한 목적으로 사용하는 것으로 생각하는 경우가 많기 때문이다. 하지만 지금까지 말해왔듯 그렇지 않다. 스택, 리스트, 트리 등의 데이터 관리와 정렬, 합병, 제일 큰 원소 찾기 등의 기능은 아주 일반적인 것이다. 많은 프로그램에서 이를 직접 구현해 사용하고 있을 것이다. 표준 템플릿 라이브러리는 바로 이런 일을 대신하는 것을 목적으로 만들어졌다. 대단한 무언가가 절대 아니다. 사용자는 단지 자신이 사용할 컨테이너와 알고리즘을 필요에 따라 선택하고, 사용하기만 하면 되는 것이다.

템플릿(Template)이라는 이름 때문에 쉽게 범접할 수 없는 어려움이 느껴지지만 템플릿의 기본 기술을 사용할 수 있는 정도만 파악한다면 표준 템플릿 라이브러리를 사용하는 것은 그다지 어렵지 않다. 오히려 사실 이제 막 C++ 언어를 배우려는 개발자는 표준 라이브러리를 사용하는 것부터 시작하는 편이 좋다. 표준 라이브러리는 직관성이 높은 라이브러리인 동시에 높은 수준의 연산을 지원해 주기 때문이다. 그래서 C++ 언어 문법의 가장 기초적인 것만 파악하고 있어도 표준 라이브러리를 사용하여 프로그램을 작성하는 데는 전혀 문제가 없다. 오히려 반드시 해야 할 에러 처리 등을 생각하면 이를 직접 수행하는 것보다 표준 라이브러리의 에러처리에 의존하는 것이 훨씬 더 이득이 된다. 그렇기 때문에 많은 전문가들이 표준 라이브러리를 사용하는 것에서부터 C++ 언어를 시작하기를 추천한다.

이 외에도 작업 환경에 대한 지원 때문에 표준 템플릿 라이브러리의 사용을 꺼려하기도 한다. 가장 일반적인 환경이 비주얼 C++, g++ 등일 텐데, 표준 템플릿 라이브러리 자체가 길어야 10여년 전에 탄생되었던 점을 감안하면 이들 환경에서 표준 템플릿 라이브러리를 제대로 지원하기 시작한 것은 그다지 오래된 일이 아니다. 그래서 애써 표준 템플릿 라이브러리를 배워 프로그램에 적용하더라도 번역이 안되거나 거의 암호화된 수준의 에러 메시지를 만나 당황했을 것이다. 하지만 비주얼 C++ 6.0 버전 이상, .NET, g++3.3 버전 등의 비교적 최신 컴파일러에서는 이제 표준 템플릿 라이브러리를 거의 완벽하게 지원하고 있다. 아직 세부 구현에 실수가 있긴 하지만 대다수의 실제적인 적용에 있어 심각한 문제를 초래하는 경우는 거의 없다. 또한 STLFilt 등의 널리 알려진 무료 진단 도구는 복잡한 에러 메시지를 간단한 형태로 바꾸어 에러 메시지의 내용을 쉽게 이해할 수 있는 형태로 바꿔주므로 이런 도구를 적극적으로 이용하는 것도 좋다.

뜻밖에도 개발자 중에는 왜 표준 템플릿 라이브러리를 사용하지 않는가에 대한 대답으로 “MFC를 사용하는데 또 STL을 사용해야 할 이유가 있는가?”라고 반문하는 경우가 많았다. 그런데 이는 표준 템플릿 라이브러리에 대한 잘못된 이해로 생기는 의문이다. 표준 템플릿 라이브러리는 MFC(Microsoft Class Library)와 아무 관계가 없다. 아니, MFC와 표준 템플릿 라이브러리를 함께 사용해야 더 강력한 프로그램을 작성할 수 있다. MFC와 표준 템플릿 라이브러리가 추구하는 목적이 근본부터 다르다. 표준 템플릿 라이브러리는 컨테이너, 알고리즘 등 데이터 구조와 관련된 인터페이스를 플랫폼 독립적인 방법으로 제공하는 것이 주목적이지만, MFC는 GUI(Graphics User Interface)를 윈도우라는 실행 환경에서 쉽게 프로그램화할 수 있도록 하는 것이 주목적이어서 서로 겹치는 부분이 거의 없다. 더구나 이들을 구성하는 패러다임 역시 전자는 명령형, 제네릭, 함수형 패러다임을 섞어 쓴 반면, 후자는 개체지향적이다. 물론 비슷한 목적의 요소가 다소 있기는 하다. 문자열을 관리하는 CString과 표준 라이브러리의 string, 리스트를 구현한 CObList와 표준 라이브러리의 list 등이 그것이다. 하지만 적어도 필자의 경험으로는 표준 라이브러리가 MFC 라이브러리보다 훨씬 나은 방법을 제공하고 있으며, 아마 표준 라이브러리를 사용한다면 여러분도 나와 같은 경험을 하게 될 것이다.

표준 템플릿 라이브러리를 아직 사용하지 않는 C++ 프로그래머라면 지금부터 접해보라고 자신있게 말할 수 있다. 먼저 시퀀스 컨테이너의 일종인 vector를 malloc으로 관리하는 동적 배열을 대체하는 것으로부터 시작해 보라. 전혀 새로운 C++ 세계를 경험할 것이다.


http://network.hanbitbook.co.kr/view.php?bi_id=984
"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/05/17 17:26 2007/05/17 17:26
Posted by webdizen
Tags Algorithm, C++Keyword C++, Container, Functor, Iterator, STL, 알고리즘, 이터레이터, 컨테이너, 함수 개체
No Trackback No Comment

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

Leave your greetings.

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

«Prev  1  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

  • 데이터 암호화
  • Logo
  • 공유 객체
  • Prado Framework
  • Filtering
  • 라이브락
  • Stratos Framework
  • 여행
  • 마주앙 미셀
  • 시스템 관리
  • Firefox
  • 발성
  • MySQL
  • 크기
  • Makefile
  • 성능
  • NULL
  • ASCII Character
  • Child Window
  • Active Directory

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.