Introduce the study of C ++ STL's preparation knowledge and STL's related background knowledge, suitable for beginners

xiaoxiao2021-04-08  268

Table of Content 1 STL: Solution some questions

1.1 One of the most concerned issues: What is STL 1.2 chase roots: STL's history 1.3 thousand silk contacts

1.3.1 STL and C 1.3.2 STL and C Standard Library 1.3.3 STL and GP, GP and OOP 1.4 STL Different Implementation Versions

1.4.1 HP STL 1.4.2 P.J. Plauger STL 1.4.3 Rouge Wave STL 1.4.4 Stlport 1.4.5 SGI STL 2 Bull Knife Try: and look at a simple routine

2.1 Pillage 2.2 routines

2.2.1 First Edition: Prehistoric Age - Transfer of Turbuo 2.2.2 Second Edition: Industrial Age - Componentization of Components 2.2.3 Third Edition: Aestheticism 2.3 History 2.4 How to Run

As part of the C standard, STL should be penetrated in the corner of the C program. STL is not the pet in the laboratory, nor is the furnishings on the programmer table, and her exciting is not a flower. This tutorial aims to spread and popularize STL's basic knowledge. If you can take this opportunity to promote some things that STL can do, it is also a pleasant thing.

1 First STL: Solution Some Questions 1.1 One Most Careful Question: What is STL1.2 Tracing Tripper Tracing: STL's History of 1.3 Thousands of Things 1.3.1 STL and C 1.3.2 STL and C Standard Library 1.3.3 STL and GP, GP, GP and OOP1.4 STL Different Implementation Version 1.4.1 HP STL1.4.2 PJ Plauger Stlhttp: //www.dinkumware.com. Visual C . Net (ie VC7.0) in Visual Studio.NET, has improved the support of C standards, and has more MAP containers, MultiMap containers, and MultiMap containers and Set container. "What is STL?", If you know very little about STL, then I think you must know the answer to this question, frankly, to expect to use a short number to explain this problem, Easy. Therefore, if you still feel like you understand after reading this section, you don't have to worry. After reading the follow-up content, I believe that you have a understanding of STL, which will be more clear, accurate and complete. However, what is it a bit like a bit like a bad expression? :) I don't know if you have had such an experience. When you are ready to complete the homework furnished by the data structure, or when you add a new feature to a software project you are responsible, you find that you need to use a list (List) or a mapping table ( Map), but there is no ready-made code. So the manual implementation of List or MAP is inevitable before you start formally considering the program function. So ..., I finally completed the task. Perhaps, as a programmer with higher raising programmers, you still refuse (or a good life like to be lazy :), because you will think, if you still have this situation, what should I do? No need to do the same thing again! If the above situation is happening every day, it may be a bit exaggerated. However, if you say the entire software field, it is indeed a goal for decades - Reusability, which looks no exaggeration. From the earliest process-oriented function library, to object-oriented programming ideas, to various component technologies (such as: COM, EJB), to Design Pattern, and so on. STL is also a similar thing, while behind it contains a new programming idea - generic programming. Continue to mention the example mentioned above, if you keep List or MAP, you are being pleased. And slow, if the next List is not floating in the floating point, is it integer? If your MAP always doesn't satisfy you in efficiency and sometimes you will still have some bugs? How do you face these problems? Using STL is a good choice, it is true that STL can solve these problems mentioned above, although you can seek other methods. Half a day, what is STL? STL (Standard Template Library), the standard template library, is an industrial intensity, efficient C library.

It is accommodated in the C Standard Library (C Standard Library), the latest in the ANSI / ISO C standard is also a very revolutionary part. The library contains many basic data structures and basic algorithms commonly used in computer science. Provided an expandable application framework for the majority of C programmers, which reflects the reuse of software. This phenomenon is similar to MFC (Microsoft Foundation Class Library in Microsoft Visual C , or VCL (Visual Component Library) in Borland C Builder. For this, everyone will not be unfamiliar. From a logical level, it reflects the generic programming of generic programming in STL, introduces many new nouns, such as Requirements, Concept, Models, Containers (Container) ), Algorithmn, iterator, etc. Like polymorphism in OOP (Object-Oriented Programming), generics is also a software multiplexing technology. From the implementation level, the entire STL is implemented in a type parameterized method, which is based on a language characteristic-template (Template) that does not appear in the early C standard. If you review any version of the STL source code, you will find that the template as the cornerstone constituting the entire STL is a thousand truth. In addition, there are many new features of C to provide convenience for STL implementation. I don't know why you feel so many terms, I hope that you will not be unhappy. If you don't know much about the majority of them, please rest assured that these nouns will be discussed one by one in subsequent content. Just as mentioned. Interestingly, there is another explanation for STL - Stepanov & Lee, the former refers to the founder of Alexander Stepanov, STL; and the latter is Meng Lee, she also makes STL to implement the hero, the first STL finished product is They work together. This method originated from March 1995, Dr.Dobb's Journal, the famous technical book writer Al Stevens an interview with Alexander Stepanov. When I get a new friend, most people can't help but want to know the past. This section will take you simple review of STL's past. Alexander Stepanov, known as the father of STL, was born in Moscow, Soviet Union, early in the second half of the 1970s, he has begun to consider that in the premise of guarantee efficiency, the possibility of abstracting the algorithm from many specific applications This is the prototype of the generic thinking. In order to verify your own thoughts, he and the Professor of New York State University, David Musser, a professor David Musser, a professor, TETRE, jointly developed a language called Tecton. Although this attempt eventually did not achieve practical results, it gave the STEPANOV a big revelation.

In the subsequent years, he has also established some large-scale libraries with the David Musser et al. This time, Alexander Stepanov has begun to realize that some of the problems existing in the object-oriented program design idea, such as the defects of the abstract data type concept. Stepanov hopes to gradually form a conceptual framework for software design through the classification of each component in the software. Arkant Stepanov works in Bell Laboratory, Alexander Stepanov works in the Bell Laboratory. Unfortunately, the C language at that time has not introduced the template's grammar. Now we can clearly see that the template concept is implemented in STL implementation. When it is, it is not selected when using the inheritance mechanism. Despite this, Stepanov has developed a huge algorithm library. At the same time, in the process of CCPANOV, Stepanov begins noticing in the C / C language to achieve its generic thinking in the process of the top masters of Andrew Koenig and the top masters of Bjarne Stroustrup (founders of the C Language). The potential advantages have been made. In terms of pointers in C / C , its flexible and efficient use, making later STLs maintaining high efficiency while achieving genericization. In addition, iterative agencies that occupy an extremely important position in STL are abstractions from the C / C in the Native Pointer. In 1988, Alexander Stepanov began to enter HP's Palo ALTO laboratory work, in the next 4 years, he is engaged in the work of disk drives. Until 1992, he returned to the research work of genericization algorithm due to a research project established by the Laboratory Bill Worley. After the project was built, participants gradually decreased from the initial 8, and finally only two people left - Stepanove himself and Meng Lee. After a long time, the ultimate, the belief and sweat is exchanged in a huge runner containing a large amount of data structure and algorithm components. This is the prototype of the current STL (also an implementation version - HP STL) of STL. In 1993, At that time, the Andrew Koenig in Bell Lab has seen Stepanove's research results, which is very excited. With his encouragement and help, Stepanove has a relevant speech for the ANSI / ISO C Standards Committee (entitled "The Science Of C Programming" in September (entitled "The Science Of C Programming") tells its ideas. Then, in March, in the San Diego meeting, a proposal submitted to the Committee to make STL a part of the C standard library. Although this proposal is very large, it has reduced the possibility of passing, but due to its new idea, the voting results are delayed for the proposal with the significant opinion. Subsequently, under the help of everyone, including Bjarne Stroustrup, Stepanove has improved STL. At the same time, an abstract module of encapsulating memory mode information is added, that is, the Allocator in STL, which makes most of the STL can be independent of the specific memory mode, which is independent of the specific platform.

At the Waterloo meeting in the same summer, the members were in favor of 80%, and 20% objected, and finally passed the proposal, decided to formally incorporate STL in the C standardization process, and STL was placed in the meeting's work file. Since then, STL finally became an important member of the C family. Thereafter, as the C standard is constantly improving, STL is constantly evolving. Until 1998, the ANSI / ISO C standard officially finalized, STL is always an indispensable part of the C standard. After you understand the STL's past, some nouns have been constantly emerged in your brain, STL, C , C standard library, generic program design, object-oriented programming ... What does these concepts mean? What is the relationship between them? If you want to know some details, you may have the answer you want to get. There is no STL without the C language, which is not too much. In general, STL acts as a genericized data structure and algorithm library, does not involve specific languages ​​(of course, in C , it is called STL). That is, if the condition is allowed, it can be implemented in other languages. The conditions mentioned here are mainly a grammar mechanism similar to "template". If you have not skip the content of the previous section, you should see that Alexander Stepanov is early to use a variety of programming languages ​​before choosing a C language as an implementation tool. However, why do you enduring this historic task in the end or C ? The reason is not only the above conditions, but also the superior features of C exhibited in certain aspects, such as efficient and flexible pointers. But if C is seen as an OOP (Object-Oriented Programming, the Object-Oriented Programming) language (in fact we generally think so, isn't it?), Its powerful inheritance mechanism is not given to STL How much is it to help? In the STL source code, there is no too much complex inheritance relationship. Inherited thoughts, even object-oriented ideas, is not enough to achieve generic libraries like STL. C only results in the birth of STL only after the "template" is introduced. This is why, using other more purely object-oriented languages ​​than C unable to achieve an important reason for generic ideas. Of course, things are always changed, like Java in this regard, is a good example, JDK1.4 has already joined the generic characteristics. In addition, STL has promoted the development of C , especially template mechanisms. For example: Template Function Partialization, it is used to provide a series of specialized versions for a particular template function in a specific application. This feature is followed by the ANSI / ISO C Standard Commission, and the Bjarne is discussed by Bjarne and Stepanov, and the Bjarne will be suggested to the Committee. This allows some algorithms in the STL to select a non-generalized manner when processing a special case, thereby ensuring the efficiency of the execution. STL is a subset in the latest C standard library, which accounts for approximately 80% of the entire library.

As a template that plays key roles in the STL process is filled with almost the entire C standard function library. Here, we need to see which contents contain in the C standard library, which are those belonging to a standard template library (ie STL). The C standard library provides an extensible basic framework for C programmers. We can achieve great convenience from it, and we can expand it by inheriting existing classes, compliance with intervenes, algorithms, iterative materials, etc. It roughly includes the following components: C Standard Function Library, basically maintaining good compatibility with the original C language library, although some slightly change. People will always can't help but have a beautiful year, if you have been a C programmer, you must feel deeply. Perhaps you will make you feel strange, that is, there are two sets of C standard libraries, a set of .H extensions (such as ), and another set is not For example, ). They don't have much different. Language Support section, contains some definitions of standard types and other features, which are used in other parts of the standard library or in specific applications. Diagnostics section provides three ways for program diagnostics and error, including exception handling, assertion, error code, error code. General utilities section, this part of this part provides support for the other parts of the C standard library, of course, you can also call the appropriate functions in your own program. For example: Dynamic Memory Management Tools, Date / Time Processing Tools. Remember, the content here has also been generalized (ie, a template mechanism) is used. String section, used to represent and process text. It provides a rich feature. In fact, the text is a String object, which can be seen as a character sequence, the character type may be char, or Wchar_t, etc. String can be converted to a char * type, which can be a peaceful coexistence with the previously written C / C code. Because at that time, there was no other than CHAR *. INTERNATIONALIZATION section And time representation, numerical and currency processing, etc.. After all, in China and in the United States, people express their habits of the date. A containers section, an important part of STL covers many data structures, such as the list previously mentioned, and: Vector (similar to the number of magnifications), Queue (Queue), Stack (Stack ) ... String can also be seen as a container, and the method suitable for containers is also applicable to String. Now you can easily complete the homework of the data structure course.

Algorithms section, an important part of STL contains approximately 70 general algorithms for manipulating various containers, while also manipulating an array. For example, Find is used to find an element equal to a particular value in the container, and for_each is used to apply a function to each element in the container, and SORT is used to sort the elements in the container. All of these operations are made under the premise of performing efficiency, so if the program becomes efficient after you use these algorithms, you must first do not doubt these algorithms itself and carefully check the other places of the program. An important part of the iterators section, STL, if there is no iterator, the container and algorithm are unable to combine such perfect. In fact, each container has its own iterator, only the container knows how to access your own elements yourself. It is a bit like a pointer, and the algorithm is positioned and controlled in the container through an iterator. A NuMerics section contains some mathematical computing functions, providing support for complex operations. Input / Out / Output part, is the Iostream section in the templated original standard library, which provides basic support for the input and output of the C program. It is functionally compatible with the original Iostream and has increased the mechanism for exception processing and supports internationalization. Overall, in the C standard library, STL mainly includes containers, algorithms, and iterators. String can also be counted as part of the STL. Figure 1: STL and C Standard Library

As mentioned earlier, behind the STL contains the idea of ​​genericization programming (GP), in this idea, most of the basic algorithms are abstract, generalized, independent of the corresponding data structure, Used to handle various different situations in the same or similar way. This idea and object-oriented programming ideas (OOP) are not the same, because more pay more attention to the abstraction of the data, the so-called abstract data type (Abstract Data Type), and algorithm is usually attached to data Types. Almost all things can be seen as class or object (ie, instances), usually, what we see is included as a member function (member function), classes, classes, classes, complicated complex complexity Inheritance system. Although in a programming language like C , you can also use global functions to represent algorithms, but in language similar to Java, the global function has been "Ban". Therefore, it is quite difficult to simulate GP ideas with Java. If you have an impression on the aforementioned STL history, you should remember that Alexander Stepanove has used OOP-based language to tries to implement GP ideas, but the effect is not good, including the C language before the introduction of the template. Standing on the shoulders of the giant, we can conclude that the ideas reflected in OOP are indeed different from GP's ideas. C is not a purely object-oriented programming language, its wonderful place is that both OOP and all GPs. For the latter, the template has a sweat work. In addition, it is necessary to point out that although GP and OOP have many different, this difference is not to "water fire is not allowed". Also, when actually use, the combination of both is often more effective in solving problems. The STL itself as a GP thought instance is a good example. If there is no inherit, I don't know what STL will look like, and there seems to be no other experiment. I believe that your sense of sensibility to STL should be improved, it is to do some actual work, then we first understand the different version of the STL. The STL in the ANSI / ISO C file is only a standard that is only described on paper. For many C compilers, they need to have their own actual STLs, which are more or less implementation, which is described. Can be used for us. There are many reasons why there are many reasons, there are historical reasons, and the reasons for the manufacturers of compilers. Here are a few common STL implementation versions. HP STL is the root of all other STL implementations. It is a STL's parent Alexander Stepanov in HP's Palo ALTO laboratory, and the Meng Lee is completed, and it is the first STL implementation version (see Section 1.2). This STL is open source, so it allows anyone to use, copy, modify, publish, and sell the software and related documents, provided that the version information and authorization information of HP STL must be added to all related files. I have rarely use this version of STL now. P. J. Plauger STL belongs to a personal work, implemented by P. J. Plauger, is a inheritance version of HP STL, so there is a relevant statement of HP STL in all of its header files, as well as P. J. Plauger my copyright statement.

P. J. Plauger is the early implementation of the Stdio library in Standard C, and is now the editor of C / C User's Journal, maintains a good relationship with Microsoft. P. J. Plauger STL is used in Visual C for Microsoft. In the same type of version under the Windows platform, its performance is good, but the Queue component (queue, a container) is not ideal, while the support of Visual C for C language standard is not very good (at least until VC6.0, or Thus), the performance of PJ Plauger STL is therefore affected to some extent. In addition, the source code readability is poor, you can find all source files (such as: C: C: / Program Files / Microsoft Visual Studio / VC98 / include) in the VC's INCLUDE subdirectory. Because not open source, these source code cannot be modified and sold, and the current P.J. Plauger STL provides related services by Dinkumware, see 1.4.3 Rouge Wave Stlhttp://www.rougewave.com. Unfortunately, this version has not been updated for some time and is not fully compliant. Therefore, in Borland C Builder 6.0, its status is replaced by another STL implementation version --stlport. But considering compatibility with previous versions, C Builder 6.0 still retains Rouge Wave STL, just if you want to see its source code, you need to find it in other directories (such as: c: c: / program files / borland / cbuilder6 / Include / ilstl. Rouge Wave STL is implemented by Rouge Wave, is also a inheritance version of HP STL. In addition to the relevant statement of HP STL, there is a copyright statement of Rouge Wave. At the same time, it is not an open source, so it cannot be modified and sold. This version is adopted by Borland C Builder, you can find all header files (such as: c: / include) in the C Builder's INCLUDE subdirectory. Although the performance of Rouge Wave STL is not very good, because C Builder's support is good for C language standards, it is improved to a certain extent. In addition, the readability of its source code is better. You can get more detailed information from the following website: 1.4.4 StlportHttp: //www.stlport.org, you can download its source code for free. Stlport has been accepted by the C / C Technical Committee as an industrial standard and supports on many platforms. Depending on the test STLPORT is faster than the STL in the VC. More compliant than the Rouge Wave STL, it is also easier to transplant. Borland C Builder has added support for Stlport in its version 6.0, which uses Stlports that are 4.5, C Builder 6.0 also provides STLPORT instructions.

You can find all header files (such as: c: / include / stlport) in C Builder's Include / Stlport subdirectory (such as: c: / code / stlport). Stlport originated from a development project of Russian Boris Fomitchev, mainly used to transplant the basic code of the SGI STL to other mainstream compilers such as C Builder or Visual C . Because the SGI STL belongs to the open source, STLPORT has the right to do so. The latest version of Stlport is 4.5. You can get more detailed information from the following website: 1.4.5 SGI Stlhttp://www.sgi.com, you can download its source code for free. The latest version of the current version is 3.3. The SGI STL is implemented by Silicon Graphics Computer System, Inc, its designer and writers include Alexander Stepanov and Matt Austern, which is also a inheritance version of HP STL. It belongs to the open source, so you can modify and sell it. SGI STL is adopted by GCC (C compiler under Linux), you can find all header files (such as: C: C: / Cygnus / Cygwin-B20 / Include / G / include) in GCC's INCLUDE subdirectory. Since GCC has a good support for C language standards, the performance of SGI STL is quite excellent on the Linux platform. In addition, the readability of its source code is also very good. You can get more detailed information from the following website: Figure 2: Spectrum of STL family

2 cattle knife Try: and look at a simple routine 2.2 primary 2.2 routines 2.2.1 First Edition: Prehistoric Age - Transmission No. 2.2.2 Second Edition: Industrial Age - Componentization Great Production 2.2.3 3 edition: Aestheticism's masterpiece 2.3 History evaluation 2.4 How to run if you are a pure practical, maybe you can start from here, because you provide an example program, it can bring you Use the most direct feelings of STL. Yes, talking to their paper, it is better to direct, actually operate. However, it is necessary to remind, if you are trying to taste this chapter when you are interested, you can combine the previous chapter as a piece of food, it will be better. You will find that the advantages of the STL mentioned earlier are exactly certified here. The second half of this chapter will demonstrate the specific operation method of the above sample program, and what you need to pay attention to in some mainstream C compilers. I am very regrettable, I have to abandon the classic example of "Hello World", although it is not only cited by various textbooks that introduce the computer language, almost a default "standard". The reason is that it is too simple, so that it does not have representative and unable to show the huge charm of STL. I chose a slightly complicated example, and its general function is to read some integer data from the standard input device (typically the keyboard), then sort them, and finally output the result to the standard output device (generally the display screen). This is a typical process, the program itself has almost all of the basic features of a system: input processing output. You will see three different versions of the program. The first is that there is no normal C program that uses STL, you will see that it seems to be simple, it takes more strength, but not there is no problem (it really doesn't want to be good). The main part of the second program uses the STL feature, at which point the problem encountered in the first program can be solved. At the same time, you will find that after the STL, the program becomes simple and clear and easy to read. The third program uses the STL's functionality to, you can see that almost every line of code in the program is related to STL. This opportunity is not always visible everywhere, which shows almost all basic components in STL, although this seems to be a bit too much. There is a need to explain: The purpose of this routine is to demonstrate how to use STL in C programs, and we hope to prove that STL is really good. Some STL basic components used in the program, such as: Vector, sort (a sorting algorithm), you only need a rough concept, this does not affect the meaning of reading code and understanding procedures. . Many people are very interested in the operation mode of the GUI (graphical user interface), which is no wonder that the beautiful interface will always be pleasing. But unfortunately, there is no addition to these features here. This is easy to explain, and the GUI characteristic is added to the supplied, it is a bit inverted for this simple sample program provided. This will make the code amount of the program suddenly swell sharply, and the core part of the problem can be determined to be submerged in many unrelated code (you need to get great energy to handle the keyboard or the mouse response). And more standardized things).

Even if you have an IDE-based (integrated development environment) based on Borland C Builder, the process of interface is simpler (frame code is automatically generated). Please note that we talk about it here is part of the C standard (the first letter of STL illustrates this), it does not involve specific development tools, it is almost compiled on any C compiler. The code passed. After all, in Microsoft Visual C and Borland C Builder, the processing code for GUI is different. If you want to know the details of these GUI, I am afraid that there is no answer you want to get, you can find other related books. In STL, there is no birth to the "dark age", C programmers to complete the functions mentioned earlier, need to do a lot (but this is better than the C procedure, it seems better), the program is approximately as follows: // name: eXample2_1.cpp // alias: Rubish

#include

#include

INT COMPARE (const void * arg2);

Void main (void)

{

const Int max_size = 10; // A number of arrays allows the maximum number of elements

INT NUM [MAX_SIZE]; // Integer array

// Read the integer from the standard input device, and enter the number of numbers,

/ / Until the input is not integrity data

Int n;

For (n = 0; cin >> NUM [n]; n );

Quick-sort function in // C standard library

Qsort (NUM, N, SIZEOF (INT), Compare;

// output the sort result to the standard output device

For (int i = 0; i

COUT << NUM [i] << "/ n";

}

// Compare the size of the two numbers,

// If * (int *) arg1 ratio * (int *) Arg2 is small, return -1

// If * (int *) arg1 ratio * (int *) Arg2, return 1

// If * (int *) arg1 is equal to * (int *) arg2, return 0

INT COMPARE (Const Void * Arg1, Const Void * Arg2)

{

RETURN (* (int *) arg1 <* (int *) arg2)? -1:

(* (int *) arg1> * (int *) arg2)? 1: 0;

}

This is a traditional C program with a traditional style with STL. Because the comment of the program is very detailed, I don't need me more explanation. In general, this program looks not very complicated (there is not much function). Just, that compare function, it looks a little hard. Pointing to its function pointer is sent into the QSort function as the last actual parameter, QSort is a function in the C library stdlib.h. The following is a function prototype of QSort: void Qsort (Void * Base, SIZE_T NUM, SIZE_T WIDTH, INT (CONST VOID * ELEM1) (Const Void * Elem2);

It looks a bit awesome, especially the last parameter. Probably, the first parameter indicates an array to be sorted (such as: NUM in the program), the second parameter gives the size of the array (QSort does not have enough intelligence predict the actual size of the array you pass. ), The third parameter gives the size of each element in the array in bytes. Finally, the long guy gives the way to compare elements when sorting (still because of QSort IQ). The following is the result of a certain run: Enter: 0 9 2 1 5

Output: 0 1 2 5 9

There is a problem, this program is not as good as it looks so strong. If the number of numbers we entered exceeds the upper limit specified by max_size, an array critical problem occurs. If you run this program in a console mode in the visual C IDE environment, an error dialog box is popped up. This problem is very serious, serious enough to enable you to start re-examining the code. In order to make up the defect in the program. We have to consider using one of the following three programs:

Using large-capacity static array assignments. Limited the number of input data. Dynamic memory allocation. The first solution is relatively simple, and you do just changing max_size, such as: 1000 or 1000. However, strictly speaking this does not finally solve the problem, and the hidden dangers still exist. If someone is patient enough, you can make your corrected program crash. In addition, allocate a large number, usually a waste space, because in most cases, some space in the array is not utilized. Let's take a look at the second solution. By adding a qualified condition in the first FOR cycle, the problem can be resolved. For example: for (int N = 0; cin >> Num [n] && n

#include

#include

#include

Using namespace std;

Void main (void)

{

Vector Num; // STL VECTOR container

Int element;

// Read the integer from the standard input device,

/ / Until the input is not integrity data

While (CIN >> ELEMENT)

Num.push_back (element);

Sampling algorithm in // STL

sort (Num.begin (), Num.end ());

// output the sort result to the standard output device

For (int i = 0; i

COUT << Num [i] << "/ n";

The main part of this program uses STL's components, it seems to be more simple than the first program, you can't find the annoying Compare function. Can it really run well? You can try it because the runtime of the program is almost roughly, so this is slightly. I can guarantee you that this program is so robust. However, you may have not fully understood the code of the program, so I need to explain it to you. After all, this trick has become too fast, and the first programs, a blink of an eye, the familiar code familiar to the old C programmers will not see, and some fresh things are some. The first three lines of the program are the header files that provide all C features (including input / output processing, containers and algorithms in STL). Don't care about that .h, not my negligence, the program guarantees that you can compile, as long as your C compiler supports the relevant part of the standard C specification. You only need to think of them as some ordinary C header files. In fact, it is exactly. If you are interested in this change, you can pay attention to your side. It can also ignore the existence of the fourth line. Joining that statement is just to indicate that the program references this standard name space (Namespace), because those in STL are all contained there. The compiler can allow you to use those interesting features through this line declaration. The vector is used in the program, which is a standard container in STL, which can be used to store some elements. You can put the vector

Understand int [?], A integer array. The reason why the size is unknown because the Vector is a container that can dynamically adjust the size. When the container is full, if the element is placed, the vector will quietly expand its capacity. Push_back is a class member function for the Vector container to insert an element in the end of the container. What the first While loop in the main function is to continuously insert integer data at the end of the VECTOR container while automatically maintaining the size of the container space. SORT is the standard algorithm in STL to sort elements in the container. It requires two parameters to determine which range within the container can be sorted. Here you can use the other two class member functions of the Vector. BeGin () is used to point to the head end of the Vector, and End () is directed to the end of the VECTOR. There are two problems here, what is the return value of Begin () and End ()? This involves another important part of STL - iterator, but it does not need to do a detailed understanding of it. You just need to treat it as a pointer, a pointer to integer data. The corresponding Sort function declaration can also be regarded as a Void Sort (INT * First, INT * Last), although this is actually inaccurate. Another problem is related to the END () function, although it said that its return value points to the end of the Vector, this statement cannot be correct. In fact, its return value is pointed to one position in the back of the vectors, that is, the so-called Pass-the-end value. This sounds a little means of consistency, but it is not necessary to care, here is just a little one. Overall, what is done by the Sort function is to sort the elements in the intersection array, as the QSort in the first program, but compared to QSort, Sort seems to be simple. The final output section of the program, where the vector can be completely fake, which is the same as the element's access method is simply in the ordinary C built. That size function is used to return the number of elements in the vector, which is equivalent to the variable n in the first program. These two lines of code can be intuitive without me to explain. I think my patience should make you roughly understand the procedure above, in fact, the use of STL makes the logic of the program clearer, making the code easier to read. I will don't understand the meaning of Begin, End, and size (unless he does not understand English)? Try to run, look at the effect. Try more to enter a number of numbers to see if the array of becomes occur. Practice has proved that the program is working well. Yes, because the VECTOR container maintains its own size, C programmers don't have to worry about the dynamic memory allocation, the pointer's error will bring a lot of trouble, while the program will become lengthy. This is the shortcomings of the third program in front. Review your first STL version of the C program, review the benefits of the first chapter on STL: easy to use, industrial strength ..., compare the first version of the program, I want You should experience it! The development of the situation is sometimes trend to extreme, which is like this in those americanists. First, declare that I am not a beautifulist, providing the upgrade version of the second edition, is completely in order to make you feel more about the charm of STL. After reading the third edition, you will strongly feel this. Maybe you will also become a beautifulist, at least in STL. This should not be my fault, because the power is in your hands. Let's take a look at this out of print C program. // name: eXample2_3.cpp // alias: AESTHETIC VERSION

#include #include

#include

#include

Using namespace std;

Void main (void)

{

TypedEf vector int_vector;

TypedEf istream_iterator iStream_iTR;

Typedef ostream_iterator ostream_iTR;

Typedef back_insert_iterator back_ins_itr;

// STOR VECTOR container

INT_VECTOR NUM;

// Read the integer from the standard input device,

/ / Until the input is not integrity data

Copy (istream_i (cin), iStream_i (), Back_ins_itr (NUM));

Sampling algorithm in // STL

sort (Num.begin (), Num.end ());

// output the sort result to the standard output device

Copy (Num.begin (), Num.end (), Ostream_i (Cout, "/ N"));

}

Almost every line of code is related to STL in this program (except for main and the pair of curly brackets, it also comments), and it contains almost all of the major parts in STL (container Container, Iterator Iterator, Algorithm) Algorithm, adapter adaptor, the only regret is to have less functions. Remember the basic characteristics of a typical system mentioned in the beginning? - Input process output. All of these features, in the above program, is only implemented by three lines of statements, where each line statement corresponds to one. For the operation of the data, the combination between the algorithm and the container is as easy as the wood is as easy as the wood, and the system's coupling degree is lowered. This is the great force of STL that shines with generic light. So simple, so clever, so amazing! Just like magic, it is ever, I can't touch it again. How to achieve it? Why is you clear when you look at the second edition of the program, fall in five miles (happiness). Please pay attention to the title of this place (the masterpiece of aesthetics), in the actual environment, you may not do this perfect. After all, the wishes of a beautiful wish often happen during life. It is not a good thing, at least I think so. As mentioned earlier, this program is just to showcase the unique charm of STL, you have to confess it for its excellent performance, may have only a deep STL's way of life will come out. If you are just a general use of STL, you can do this. It is really because this program is too "simple", so that I can't affirm it, before you have not fully grasped STL, I can understand the three lines of code in this area before you have not fully grasped STL. I will do my best. The iterator mentioned earlier can locate and access any element in the container. In STL, this feature is promoted. A CIN represents a data stream from the input device. From the concept, it is similar to the access function of the data stream. It is similar to the iterator in the general sense, but CIN in C is not like an iterator, The reason is that its interface and iterator interface are inconsistent (for example: ), it is not possible to value it, the value of * operations). In order to solve this contradiction, you need to introduce the concept of the adapter. Istream_iterator is an adapter that packs CIN to make it look like an ordinary iterator so that we can use it as a real paragraph to some algorithms (such as the Copy algorithm here). Because the algorithm only recognizes iterators without accepting CIN. For the first COPY function in the above program, the first parameter is expanded in the form: iStream_iterator (cin), the second parameter is expanded in the form: iStream_iterator

() (If you are unclear about typedef's syntax, you can refer to the relevant C language book). Its effect is a temporary object that generates two iterators. The previous one points to the beginning of the input data stream, and the latter is directed to "pass-the-end value". The role of this function is to "copy" to the head from the head to the end of the head to the vector.

This quasi-integer array, the first iterator is accumulated from the start position, and finally reaches the position pointed to by the second iterator. Maybe you have to ask, if the behavior of the COPY function is really like what I said, why not write it as the following? Copy (istream_iterator (cin), istream_iterator (), num.begin ()); you can do this, but there is a small trouble. Remember the array critical problem in the first edition? If you write this, you will encounter similar trouble. The reason is that when the Copy function is "copy" data, if the number of input data exceeds the range of the VECTOR container, the data will be copied to the outside of the container. At this point, the container does not automatically grow capacity, as this is just a simply copy, not from the end. In order to solve this problem, another adapter back_insert_iterator debut, its role is to boot the COPY algorithm to insert a data at the end of the container each time. After the back_ins_itr (num) in the program is: Back_Insert_Iterator

(NUM), its effect is to generate such a severner object. I will finally finish three-third (it's not easy!), I have no difference in the second sentence and the previous version, this is slightly. As for the third sentence, OSTREAM_ITR (cout, "/ n") is in the form of ostream_iterator

(cout, "/ n"), its effect is to generate a severifier object that processes the output data stream, where its position points to the start of the data stream, and "/ n" as the division. The second COPY function will take the vector from the beginning to the end.

The content "copy" to the output device, the iterator represented by the first parameter will be taken from the start position each time, and finally reach the position indicted by the iterator represented by the second parameter. This is all content. Historical wheels always rolled forward, the civilization of the industrial era is of course advanced and developed. Review the C programs of the era, you will really feel this difference. Simple and easy, industrial strength, good portability, high efficiency, plus the third a dazzling out-of-printing process, which makes you back to STL The implication of generic thinking has some feelings. It's really fortunate, you can cross the two times, have the opportunity to see this "civilized" difference. At the same time, this should also make you more confident, so that yourself will comply with the trend of the times. Before you haven't really started to run the two programs before run, it is best to browse this section first. Here is some details of running the STL program in a specific compiler environment and provide some solutions that may encounter. Here, I selected Microsoft Visual C 6.0 and Borland C Builder 6.0 currently under Windows platform as an example. Although Visual C 6.0 is not very good for the latest ANSI / ISO C standards. However, Visual C .NET (that is, VC7.0) has improved in this regard. You can use a variety of ways to run the previous program, such as under Visual C , you can compile operation directly in the DOS command line, or you can use the console application in the VC IDE. The situation is similar to C Builder. For Visual C , if you are in the DOS command line, you first need to find its compiler. Assuming your Visual C is under C: / Program Files / Microsoft Visual Studio / VC98, the path where its compiler should be C: / Program Files / Microsoft Visual Studio / VC98 / BIN, where you can find Cl.exe file. Please add / GX and / MT parameters when compiling. If everything is normal, the result will generate an executable. As shown below: CL / GX / MT EXAMPLE2_2.CPP A parameter is used to inform the compiler to allow exception handling. The abnormality processing mechanism (ie Try ... throw ... catch syntax) is used in the PJ Plauger STL, so this parameter should be added, otherwise there will be the following warning information: Warning C4530: C Exception Handler Used, But Unwind Semantics Are Not Enabled.

The latter parameters are used to allow the program to support multi-threads, which need to use the libcmt.lib library file when linked. However, P. J. Plauger STL is not a thread safe (Thread Safety). If you use STL implementations like Stlport in a VC environment, you need to add this parameter because stlport is a thread. If you can choose a console application when you create a new project in an IDE environment.

Figure 3: Run STL program in the Visual C IDE environment

As for the settings of those parameters, they can be done by setting compilation options in the settings feature in the Project function menu item [ALT F7]. Figure 4: Set compilation parameters in the Visual C IDE environment

Sometimes, when compiling STL programs in the IDE environment, the following warning information may occur (the previous sample programs do not have this case): Warning C4786: '...': Identifier Was Truncated to '255' Characters in The Debug Information

This is because the compiler compiles when compiled in the DEBUG state, limits the length of the identifier in the program over 255 characters. If the maximum length is exceeded, these identifiers cannot be viewed and calculated during the debug phase. In a large number of template functions and template classes in the STL program, the compiler When instanting these content, the identifier generated after expanding is long (there will be more than 1,000 characters!). If you want to know this Warning, it is very simple, plus the following line code in the program: Vector string_array; // Similar to the string array variable

For such Warning, of course, it can be ignored, but there is also a solution. You can join the following line at the beginning of the file: #pragma Warning (Disable: 4786). It enforces the compiler to ignore this warning message, which is a bit rude, but it is very effective. As for C Builder, the operation mode in its DOS command line is like this. If your C Builder is installed in C: / Program Files / Borland / CBuilder6. The path where its compiler is located should be C: / Program files / borland / cbuilder6 / bin, where you can find the BCC32.exe file, enter the following command, you will have a big success: BCC32 EXAMPLE2_2.CPP

As for the IDE environment, you can select the Console Wizard when new applications.

Figure 5: Run STL program in the C Builder IDE environment

Now you can run the previous sample program on your machine. However, please don't have a lot of mouth, some details have to be invited to pay attention. Caution the compiler to leave the trap. For example, there is a line of code as follows: typedef back_insert_iterator back_ins_iTR;

Please pay attention to ">" the space in front, it is best not to save. If you regret the disk space occupied by this space, it is too disappointing. The reason is still the defect of the C compiler itself. The above code is equivalent to the following code (the compiler is also a translation work): typedef back_insert_iterator > back_ins_iTR;

转载请注明原文地址:https://www.9cbs.com/read-132698.html

New Post(0)