C ++ standard library and standard template library

Source: Internet
Author: User
Tags bitset

C ++ comes from its rich library and library function resources. The content of the C ++ standard library is defined in 50 standard header files. In C ++ development, the standard library should be used as much as possible. The direct advantages include: (1) cost: it has been provided as a standard. Why does it take time and manpower to re-develop? (2) quality: the standard library is strictly tested, correctness is ensured; (3) Efficiency: the efficiency of people has been reflected in the cost.Code(4) Good programming style: Use common practices in the industry for development.

In C ++ProgramIn design courses, especially as the first program design course, we focus on grammar, language mechanisms, and other aspects. There is a process to cultivate the program design capability. The general practice of directly entering the project through basic principles and knowledge is determined by the span. Furthermore, on the basis of understanding the basic principles, we can gradually master the knowledge of the standard library through practice. To learn the standard library, you do not need to read it carefully. Instead, you need to understand the overview in practice.

This task is to know what is not mentioned in the C ++ programming curriculum, but this part is very important to programming. At least we must be able to answer the question "What is there" first.

 

I. c ++ standard library

The content of the C ++ standard library is divided into 10 categories (it is recommended that you draw out the header files you have used or heard of during reading ):

C1. header files related to the language support function in the standard library

Header file

Description

<Cstddef>

Define macro null and offsetof, and other standard types of size_t and ptrdiff_t. The difference with the corresponding standard C header file is that null is a complementary definition of the NULL pointer constant in C ++, and the macro offsetof accepts the structure or joint type parameters, as long as they do not have non-static members of the member pointer type.

<Limits>

Provides definitions related to basic data types. For example, for each numeric data type, it defines the maximum and minimum values that can be expressed and the number of digits of the binary number.

<Climits>

Provides C style definitions related to the basic integer data type. The C ++ style of the information is defined in <limits>

<Cfloat>

Provides C style definitions related to basic floating point data types. The C ++ style of the information is defined in <limits>

<Cstdlib>

Provides macros and functions that support program startup and termination. This header file also declares many other miscellaneous functions, such as search and sorting functions, from string to numeric functions. Unlike the corresponding standard C header file stdlib. H, it defines abort (void ). The abort () function also has additional functions. It neither calls the Destructor for static or automatic objects, nor calls the function that is passed to the atexit () function. It also defines additional functions of the exit () function, which can release static objects and call the functions registered with atexit () in reverse order. Clear and close all open C streams and return control to the host environment.

<New>

Supports dynamic memory allocation

<Typeinfo>

Supports variable type identification during running

<Exception>

Exception Handling is supported. This is a possible error in the processing program.

<Cstdarg>

Supports functions that accept variable parameters. That is, when you call a function, you can send data items of a different number to the function. It defines the macro va_arg, va_end, va_start, and va_list types.

<Csetjmp>

Provides functions for C-style non-local jumps. These functions are not commonly used in C ++.

<Csignal>

Provides C style support for interrupt handling

C2. supports Stream Input/Output header files

Header file

Description

<Iostream>

Supports the input and output of standard streams Cin, cout, cerr, and clog. It also supports multi-byte standard streams wcin, wcout, wcerr, and wclog.

<Iomanip>

Provides a control program that allows you to change the stream status and output format.

<IOS>

Define the base class of iostream

<Istream>

Defines a template class for the input in the output stream cache area.

<Ostream>

Define a template class for the output of the management output stream cache area

<Sstream>

Supports Stream Input and Output of strings

<Fstream>

Supports file Stream Input and Output

<Iosfwd>

Provide Forward Declaration for input and output objects

<Streambuf>

Supports stream input and output caching.

<Cstdio>

Provides C-style input and output for standard streams

<Cwchar>

Supports multi-byte C-style Input and Output

C3. header files related to diagnostic functions

Header file

Description

<Stdexcept>

Standard definition exception. Exception is the way to handle errors

<Cassert>

Defines an assertion macro to check conditions during running

<Cerrno>

C-style error messages supported

C4. define the header file of the tool function

Header file

Description

<Utility>

Defines overloaded Relational operators to simplify writing of Relational operators. It also defines the pair type, which is a template type and can store a pair of values. These functions are used elsewhere in the library

<Functional>

Defines many function object types and functions that support function objects. Function objects are arbitrary objects that support operator () function call operators.

<Memory>

Define a standard memory distributor for containers, memory management functions, and auto_ptr template classes

<Ctime>

Supports system clock functions

C5. header files that support string processing

header file

description

<String>

Supports and defines string types, including single-byte strings (consisting of char) and Multi-byte strings (consisting of wchar_t)

<Cctype>

Single-byte character category

<Cwctype>

Multi-byte character category

<Cstring>

Provides functions for processing non-null byte sequences and memory blocks. This is different from the corresponding standard C library header file. The C library functions of several C style strings are replaced by the function pairs that return the const and non-const values.

<Cwchar>

Functions are provided to process, execute I/O, and convert multi-byte character sequences, which is different from the corresponding standard C library header file, the C-database functions of several multi-byte C-style string operations are replaced by function pairs that return values of const and non-Const.

<Cstdlib>

Provides a function to convert a single-byte string to a numeric value and between multi-byte characters and multi-byte strings.

C6. define the header file of the container class template

Header file

Description

<Vector>

Defines the vector sequence template, which is an array type that can be reset by size, which is safer and more flexible than normal arrays.

<List>

Defines a list sequence template. This is a sequence linked list. elements are often inserted and deleted at any location.

<Deque>

Defines the deque sequence template and supports efficient insertion and deletion at the beginning and end.

<Queue>

Define the sequence adapters queue and priority_queue for the queue (first-in-first-out) Data Structure

<Stack>

Define a sequence adapter stack for the data structure of the stack (before, after, before, and after)

<Map>

Map is an associated container type. It can be stored in ascending order according to the key value. Multimap is similar to map, but the key is not unique.

<Set>

Set is an associated container type used to store unique values in ascending order. Multiset is similar to set, but the value does not have to be unique.

<Bitset>

Defines a bitset template for a bit sequence with a fixed length. It can be considered as a fixed-length compact bool array.

C7. support for iterator header files

Header file

Description

<Iterator>

Define and support the iterator

C8. relatedAlgorithmHeader file

Header file

Description

<Algorithm>

Provides a set of algorithm-based functions, including placement, sorting, merging, and searching.

<Cstdlib>

Declare C standard library functions bsearch () and qsort () for search and sorting

<Ciso646>

Use and in the code &&

C9. header file for numeric operations

Header file

Description

<Complex>

Support definition and operation of complex values

<Valarray>

Supports numeric vector operations

<Numeric>

Define a set of general mathematical operations on a numerical sequence, such as accumulate and inner_product

<Cmath>

This is the C math library, which is also attached with overload functions to support C ++ conventions.

<Cstdlib>

The provided function can extract the absolute value of an integer and perform the remainder operation on the integer.

C10. localized header files

Header file

Description

<Locale>

The provided localization includes the character category, sorting sequence, and currency and date representation.

<Clocale>

C style support for localization

All header files in the C ++ standard library do not have an extension. The C ++ standard library is provided as a standard header file in the form of <cname>. In the header file in the <cname> Format standard, macro-related names are defined in the global scope, and other names are declared in the STD namespace. In C ++, you can also use the standard C library header file name in the form of name. h.

 

II. Introduction to the standard template library STL [1]

STL (Standard Template Library) is a collection of software developed by the HP lab. This technology has been around for a long time before it was introduced into C ++.

In a broad sense, STL code is divided into three types: algorithm (algorithm), container (container), and iterator (iterator). Almost all the Code uses the template class and template function, this provides a better chance of code reuse than a traditional library composed of functions and classes. In the C ++ standard, STL is organized into the following 13 header files: <algorithm>, <deque>, <functional>, <iterator>, <vector>, <list>, <map>, <memory>, <numeric>, <queue>, <set>, <stack>, and <utility>.

1. Algorithms

The function library plays a vital role in selecting data types for reusability. For example, the reusability of a square root function when floating-point numbers are used as its parameter type is definitely higher than the parameter class when integer is used as its parameter type. C ++ allows you to postpone the selection of Certain types through the template mechanism until you really want to use the template or make the template special, STL uses this to provide many useful algorithms. It completes these algorithms in an effective framework-all types can be divided into a few categories, then, you can use one type in the template parameter to replace other types in the same type.

STL provides about 100 template functions to implement algorithms. For example, the for_each algorithm calls the specified function for each element in the specified sequence, stable_sort uses the rules you specify to sort the sequence in a stable manner. In this way, as long as you are familiar with STL, many codes can be greatly simplified. You only need to call one or two algorithm templates to complete the required functions and greatly improve the efficiency.

The algorithm consists of the header file <algorithm>, <numeric>, and <functional>. <Algorithm> is the largest of all STL header files (though well understood). It is composed of a large number of template functions. It can be considered that each function is independent to a large extent, the commonly used functions include comparison, exchange, search, traversal, replication, modification, removal, reversal, sorting, and merging. <Numeric> it is very small. It only includes several template functions that perform simple mathematical operations on the sequence, including addition and multiplication operations on the sequence. <Functional> defines some template classes to declare function objects.

2. Container

In the actual development process, the importance of the data structure itself is not inferior to the importance of algorithms that operate on the data structure. When the program has a time-demanding part, the selection of data structures becomes more important.

The number of classic data structures is limited, but we often repeat some code written to implement vectors, linked lists, and other structures. These codes are very similar, it is just to adapt to the changes of different data and make some difference in details. The STL container provides us with this convenience. It allows us to reuse existing implementations to construct our own data structures of specific types. By setting some template classes, STL containers provide support for the most common data structures. The parameters of these templates allow us to specify the Data Types of elements in the container, which can simplify a lot of repetitive and tedious work.

The container consists of header files <vector>, <list>, <deque>, <set>, <map>, <stack>, and <queue>. For some commonly used containers and container adapters (which can be seen as containers implemented by other containers), you can summarize their relations with the corresponding header files through the following table.

Data Structure

Description

Implement header files

Vector(Vector)

Elements of continuous Storage

<Vector>

List(List)

A two-way linked list composed of nodes. Each node contains an element.

<List>

Dual queue(Deque)

An array of continuously stored pointers to different elements

<Deque>

Set(SET)

A red-black tree composed of nodes. Each node contains an element, which is arranged by a certain predicate acting on the element pair. No two different elements can have the same order.

<Set>

Multiple Sets(Multiset)

A set of two elements in the same order is allowed.

<Set>

Stack(Stack)

Sort the values of the last, first, and foremost

<Stack>

Queue(Queue)

Sorting of first-in-first-out orders

<Queue>

Priority queue(Priority_queue)

The order of elements is determined by a certain predicate acting on the stored value pair.

<Queue>

Ing(MAP)

By{Key, Value}A set of pairs that act on a pair of keys.

<Map>

Multiple Mappings(Multimap)

Allow ing of key pairs in equal order

<Map>

3. iterator

The iterator is the most basic part, but it is easier to understand than the previous two. There is a basic principle in software design. All problems can be simplified by introducing an indirect layer, which is completed by the iterator in STL. In summary, the iterator is used in STL to associate the algorithm with the container and acts as a viscosity and agent. Almost all algorithms provided by STL work through the iterator to access the element sequence. Each container defines its own proprietary iterator to access the elements in the container.

The iterator consists of the header file <utility>, <iterator>, and <memory>. <Utility> is a small header file that includes declarations of several templates used throughout STL. <iterator> provides many methods used by the iterator, however, the description of <memory> is very difficult. It allocates storage space for elements in the container in an unusual way, and also provides a mechanism for temporary objects generated during Algorithm Execution, the main part of <memory> is the template class Allocator, which is responsible for generating default splitters in all containers.

 

Iii. Postscript

There are also two common points of view on the use of STL. First, I think the biggest role of STL is to act as a classic data structure and algorithm textbook, because of itsSource codeIt involves many specific implementation issues. The second is that the original intention of STL is to simplify the design, avoid repetitive work, and improve programming efficiency. Therefore, it should be "application first" and do not have to go into the source code. For beginners, It is of extraordinary significance to improve their understanding of their applications by analyzing the source code.

I was thinking about designing several computer questions, so that students could understand how to use STL programming. It is a very time-consuming and laborious task to write out a question suitable for beginners, which should not be too large and have enough guidance. In addition, if there are other things that have to be emergency, the accounts will be owed, later. I would like to give some suggestions to my students that many typical C ++ textbooks provide excellent explanations for STL and you can choose one to read. When reading a book, you must start to learn to pick up and skip reading. You do not have to start from the beginning to the end to read pages one by one. At this stage, you can first learn the ity of the iterator. In C ++ programming, we recommend that you replace the vector of the array and implement the list of two-way linked lists. Vector and list seem to be related to Task 1 and Task 2 of this week. Furthermore, we will carry forward the spirit that we have always been able to practice, and promptly find some questions or self-developed questions for practice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.