STL Program Design Practice 4: Simplify input and improve maintainability
STL is stored in the STD space of the C standard library. When you use the type in the STD space, you must add std ::, otherwise you must add the following statement in the program:
Using namespace std;
Introduce STD to the global space, so you don't have to enter std ::, it is convenient for us to enter. But when you need to use a container in STL, when you are named a certain type of object, such as:
Vector
Named a constant iterative:
Vector
You have to enter a bunch of long characters, especially if the number of times is frequent. In order to reduce the input you should be named an alternate type. Such as:
TypedEf Vector
Typedef Vector
This way you can greatly reduce the input when you have a good name object, but also make the code clear.
Vect_str vstrobj;
CVECT_STR_IT CVSTR_IT;
Significant alternative types can not only reduce repeated input, concise code. The most important thing is to improve the maintenanceability of the code, just as the following package size macro is defined in TCP / IP programming:
#define packsize sizeof (struct _tagspecpack);
When you define such a macro, no matter where you need to use a package size parameter, you will be incomugged in the Packsize Macro. The benefits of this should all know that no matter how your message structure is modified, increased or decrease, your program can be compiled without any modifications, because the packsize macro always can pass the correct packet size information. . Use the TypeDef to repay the alternative type with the same integrity. Do not believe let us take a look.
Good programmers will maximize the library, high-density use libraries, bring us great convenience, avoiding duplication of labor, saving time. Especially the emergence of STL, many programmers will write the following code:
Class Custom
{
Vector
Vector
PUBLIC:
Vector
......
}
This implementation does not have a big problem (please don't say that the getData function should be written, or there is no need, just example, just explaining that it is very likely to appear in the Custom class. Vector
Let us see the extensive extensive extensive application of Typedef applications in STL, I believe that so much more convincing.
Template
Class allocator {
TYPEDEF SIZE_T SIZE_TYPE;
TYPEDEF PTRDIFF_T DIFCERENCE_TYPE;
Typedef t * pointer;
Typedef const t * const_pointer;
TYPEDEF T & REFERENCE;
Typedef const_t_reference; typedef t value_type;
......
Ok, let's talk about it, I hope to help everyone. This article is for reference only. The rush of the article, there is a typison or error, please tell us to point out ccplusplus@21cn.com, thank you first. Welcome to communicate with you and make progress together. (- Yuan Xiakai -)
Attachment:
If the friends have more STL knowledge, I hope to advise, I am grateful.