from the university began to learn C + +, up to now nearly 5 years of time and rarely used STL. Now think of really is sorry this language, also sorry precious five years of time. I love C + +, so be sure to understand it completely and comprehend it. The premise to love a person is to understand him (her), love a language is also the case. Solemnly to C + + say "Sorry!" ”。 I will do not understand your aspects of slowly make up, to really understand you. In order to learn STL better, I use learning, summing up, while blogging methods, hoping to form a study column. This can be easy to read at any time, but also can be shared to those in need. Of course in the blog, I may refer to other big Nouboyu articles. In order to respect the original, I will give the reference post of the link address. In addition, if you find errors in the article, you want to give suggestions below the comments.
Now, start learning about the important standard library STL in C + +.
STL Introduction
STL is formerly known as the "Standard Template Library", which translates to the standardized templates. STL is an important part of the C + + standard library, which is composed of six major components. These six main components are:
container (Container), Algorithm (algorithm), iterator (iterator), functor (functor), adapter (adapter), Configurator (allocator).
1. Container (Container)
Containers can be divided into three categories, namely, sequence containers, associative containers, and container adapters. The various specific inclusions are as follows:
Sequence container: Vector, List, deque
Associative containers: Set, Map, Multiset, Multimap
Adapter container: Stack, queue, priority_queue
Container |
Characteristics |
Location header File |
Vector vectors |
Access and modify arbitrary elements at constant time, with constant time complexity when inserting and deleting at the end of a sequence. The time complexity of inserting and deleting any item is proportional to the distance to the end, especially the cost of adding and deleting the vector header is relatively high. |
<vector> |
Double-ended Queue deque |
Essentially the same as the vectors, the difference is that both inserts and deletions of the double-ended queue are also constant time complexities. |
<deque> |
Table List |
Access to any element is proportional to the distance between the ends, but the insertion and deletion time complexity is constant for a location. |
<list> |
Queues Queue |
Inserts can only be done at the tail, delete, retrieve, and modify only allowed from the head. Follow the FIFO principle. |
<queue> |
Stack stack |
LIFO: Advanced post-out principle. Insert, delete, retrieve, and modify operations are allowed only at the head of the sequence, and the time complexity is constant. |
<stack> |
Set Set |
The internal implementation mechanism is a red-black tree, each node contains an element, the nodes in a certain kind of action on the elements of the predicate arrangement, no two different elements can have the same order, with the ability to quickly find. |
<set> |
Multi-Set Multiset |
is basically the same as a collection, but can support repeating elements. |
<set> |
Mapping map |
A set consisting of (key, value) pairs, sorted by a predicate on the key of a function. Has a quick Find feature. |
<map> |
Multi-mapping Multimap |
Supports a single key for multiple values, with quick Find function. |
<map> |
2. Algorithm (algorithm)
The algorithm part is mainly in the header file <algorithm>,<numeric>,<functional>. <algoritm> is the largest of all STL header files, it is composed of a large number of template functions, it can be considered that each function is largely independent, the commonly used functional scope involves the comparison, Exchange, find, traverse operation, copy, modify, remove, reverse, sort, Merger and so on. The <numeric> volume is small, and includes only a few template functions that perform simple mathematical operations on the sequence, including some operations on the sequence of addition and multiplication. <functional> defines a number of template classes that declare function objects.
3, iterators (Adapter)
Iterators are implemented with class templates. Overloaded with *,->, + +,--operators.
There are 5 types of iterators: input iterators, output iterators, front iterators, bidirectional iterators, random-access iterators.
Input iterator: Read forward (only allowed);
Output iterator: Write forward (only allowed);
Forward iterator: Read ahead;
Bidirectional iterator: Read and write to front and back;
Random iterators: Random Read and write;
4, Imitation function (Functor)
An imitation function is implemented with a class template that overloads the symbol "()". An imitation function, or a function object, is one of the six components of the STL; Although the functor is small, it greatly expands the function of the algorithm, and almost all of the algorithms have a copy function version.
For example, the Find algorithm find_if is the extension of the find algorithm, the standard lookup is two elements equal to find, but what is equal in different circumstances but need a different definition, such as address is equal, address and zip are equal, although these definitions are changed, but the algorithm itself does not need to change, It's all thanks to the faux function. A functor (functor), also known as a function object, is actually a struct that overloads the () operator, and there is nothing special about it.
As the following code defines a two-yuan-judging functor:
struct intless{ booloperator() (intintconst { return (left < right );} ;
Benefits of the functor:
1) The functor is more flexible than the general function.
2) The affine function has type recognition. Can be used as a template parameter.
3) The execution speed on the functor is faster than the function and pointer.
In STL, the most common function is the parameter of the function, or the parameter of the template.
In the STL there are its own pre-defined functor, such as all operator =,-,*, such as the ' < ' number of the functor is less.
//TEMPLATE STRUCT Lesstemplate<class_ty =void>structLess : PublicBinary_function<_ty, _ty,BOOL> { //functor for operator< BOOL operator()(Const_ty& _left,Const_ty& _right)Const { //apply operator< to operands return(_left <_right); } };
Less inheritance binary_function<_ty,_ty,bool>
template<class class _result>struct// Base class for binary functions typedef _arg1 FIRST_ARGUMENT_TYPE; typedef _ARG2 SECOND_ARGUMENT_TYPE; typedef _result Result_type;};
From the definition, you can know that binary_function knowledge makes some types of declarations, which is to facilitate security and improve reusability.
According to this rule, we can also customize the functor function:
Template <typename type1,typename type2>class func_equal: public Binary_function<type1, type2,bool>{ booloperatorconst// Here The const cannot be less { return t1 = = T2; of course, here to overload== }}
The CONST keyword modifier is because a const object can access only the const-decorated function. If a const object wants to use the overloaded () function, the compilation process will get an error.
Summary: The functor is the class of the overloaded (), and the overloaded functions are const-decorated. Custom functor must inherit Binary_function (two-tuple function) or unary_function (unary function). Where unary_function is defined as follows:
struct unary_function { typedef _a Argument_type; typedef _r RESULT_TYPE; };
5. Adapter (Adapter)
An adapter is an STL component used to modify the interfaces of other components and is a class template with one parameter (the data type of the value of the operation). The STL defines 3 forms of adapters: A container adapter, an iterator adapter, and a function adapter.
1) Container adapter: Stack (stack), queue , priority (priority_queue). with the container adapter, thestack can be implemented as an adaptation of the basic container type (vector,dequeue,list). You can think of a stack as a special vctor,deque or list container, but its operations are still limited by the properties of the stack itself. The queue and the priority_queue are similar. The interface of the container adapter is simpler, but more restrictive than a typical container.
2) Iterator adapter: An STL component that modifies the interface of an iterator defined for some base container . Both the reverse iterator and the insert iterator are part of the iterator adapter, and the iterator adapter extends the functionality of the iterator.
3) function Adapter: The function is extended by converting or modifying other function objects. This type of adapter has a negative (equivalent to a "non " operation), a binder, and a function pointer adapter. The function object adapter is to convert a function to a function object, or to convert a multi-parameter function object into a function object with fewer parameters.
For example:
In the STL program, some algorithms need a unary function as parameters, you can use an adapter to put a two-dollar function and a numeric value, tied together as a unary function passed to the algorithm.
Find_if (Coll.begin (), Coll.end (), bind2nd (Greater <int> (), 42));
The phrase is to find the first element in Coll greater than 42.
Greater <int> (), is actually the ">" number, is a 2-dollar function
The two parameters of the bind2nd require a 2-tuple function, a numeric value, and a 1-element function.
bind2nd is a function adapter.
6. Space Configurator (Allocator)
The STL Memory Configurator allocates and manages memory for the container. Unified memory management makes the availability, portability, and efficiency of STL libraries a great boost.
There are 2 types of space Configurator for Sgi-stl, a simple encapsulation of malloc and free in C, and another designed to manage small chunks of memory, using memory pool technology. The default space configurator in Sgi-stl is the second level of the Configurator.
SGI uses STD::ALLOC as the default configurator.
- The alloc separates the memory configuration from the operation of the object construction, respectively, by Alloc::allocate () and : Construct () , and the same memory release and object analysis are also separated by Alloc:: Deallocate () and::d Estroy () is responsible. This is guaranteed to be efficient because the memory allocation release and the construction analysis can be optimized based on the specific type (type traits) . For example, some types can use efficient memset directly to initialize or omit some destructors. For memory allocation Alloc also provides a 2-level allocator to handle memory allocations in different situations.
- The first Level Configurator uses malloc () and free () directly to allocate and release memory. The second level uses different strategies: when the demand memory exceeds 128bytes, it is considered large enough to call the first level configurator, and the more complex memeory pool is used to manage memory when the demand memory is less than or equal to 128bytes.
- Whether the allocal is defined as a first-level configurator or a second level, SGI also wraps an interface that enables the configured interface to conform to the standard by transferring the configuration unit from bytes to the size of the element:
template<classTclassAlloc>classsimple_alloc{ Public: Statict*Allocate (size_t N) {return 0= = n?0: (t*) alloc::allocate (n *sizeof(T)); } Statict* Allocate (void) { return(t*) Alloc::allocate (sizeof(T)); } Static voidDeallocate (t*p, size_t N) { if(0! = N) Alloc::d eallocate (P, n *sizeof(T)); } Static voidDeallocate (t*p) {Alloc::d eallocate (P,sizeof(T)); }}
Memory Basic processing tool, all have commit or rollback ability.
template<classclass forwarditerator>forwarditeratoruninitialized_copy (inputiterator First, Inputiterator last, forwarditerator result); Template<classclass t>voidconst t& x); Template<class class t>const t& x)
Generic Technology
Generic technologies are implemented in the following ways: templates, polymorphism, and so on. The template is determined at compile time, polymorphism is determined by the runtime, and Rtti is also determined at run time.
Polymorphism is achieved by relying on virtual tables to look up tables at run time. For example, a class has a virtual method, then the memory start address of the instance of this class is the virtual table address, you can cast the memory start address to int*, get the virtual table, and then (int*) * (int*) Get the memory address of the first function in the virtual table, and then cast to the function type, Can be called to verify the virtual table mechanism.
Generic Programming (Generic programming, which is directly referred to as GP) is a new concept of program design, and Oo,ob,po these well-known programming ideas are different from the higher degree of GP abstraction, low coupling between components based on GP design, no inheritance, Therefore, the interoperability and extensibility of the components are very high. As we all know, any algorithm is in a particular data structure, the simplest example is the fast sorting algorithm the most fundamental implementation condition is that the sorted object is stored in the array, because the fast ordering is because of the use of the array of random storage characteristics, that can be in the unit time to exchange long-distance objects, Instead of just two objects, and if you use a linked list to store objects, because the time to get objects in a linked list is linear or o[n], this will make fast sorting lose its fast character. In other words, when we design an algorithm, we always first consider the data structure of its application, such as array lookup, table lookup, tree lookup, figure find its core is to find, but because the role of the data structure will have a variety of different representations. This close relationship between data structures and algorithms has been our previous understanding. The fundamental idea of generic design is to separate the algorithm from its data structure, that is, when we design the algorithm, we do not think about what data structures we design the algorithm will use. The ideal state of a generic design is that a lookup algorithm will act on a variety of data structures, such as arrays, tables, trees, graphs, and so on, into a generic, generic algorithm.
Relationship structure of six major components
Container The data storage space through allocator, algorithm accesses the contents of Container through iterator, functor can assist ALGORITM to complete different strategies; adapter can decorate Container , algorithm, Iterator.
Reference Links:
Introduction to STL (Standard Template Library)
STL Learning Summary
Learn stl-Introduction to STL