Author Name Jeff Bogan
This is an article that guides you how to learn STL and practice under Microsoft Visual Studio. This article spoken from STL, step by step, gradually, involved in the method of STL writing code, STL code compilation, Namespace, ANSI / ISO string in STL, Various types In container, Template, Iterator, Algorithms, Allocator, container nested, etc., the author puts some suggestions in this article, and Point out the problem that should be noted when using STL. This article covers wide, and the perspective is comprehensive. It is not only suitable for beginners to learn STL, but also the practice guidelines for the readers using STL programming.
Text This is an article that guides you to learn STL and practiced in Microsoft Visual Studio. This article spoken from STL, step by step, gradually, involved in the method of STL writing code, STL code compilation, Namespace, ANSI / ISO string in STL, Various types In container, Template, Iterator, Algorithms, Allocator, container nested, etc., the author puts some suggestions in this article, and Point out the problem that should be noted when using STL. This article covers wide, and the perspective is comprehensive. It is not only suitable for beginners to learn STL, but also the practice guidelines for the readers using STL programming. STL Introduction STL (Standard Template Library, Standard Template Library) is a good technology that needs to be mastered by people in C programming today. I think everyone who first school STL should spend some time to familiarize it. For example, there will be a lot of learning curves in a sharp rise, and some name is not easy to remember, maybe I know. The name has been used in light), however, if you have a STL, you will not feel headache. STL is more complex and powerful than MFC. STL has some of the following advantages: It is convenient to easily achieve a series of algorithms such as search data or sorting data, more secure and convenient when debugging procedures; even if people write code written with STL in the UNIX platform You can also easily Understand (because STL is cross-platform). Background knowledge Write this part is to let readers of some beginners have a good start in a challenging computer science field, not to understand the endless japanese terms and dull rules, and only those joices and rules here. It is used as a creation of STLER for entertainment. The code used in this article is mainly guided in STL practice. Some basic concepts define templates (Template) - macro (Macro) of various data types and functions such as structures. Sometimes called a cookie cutter, a regular name should be called a generic - a class template called the generic class, and a function of a function is naturally called a modest function ( Generic function. STL - Standard Template Library, some of the intelligent people written some templates now have become part of the standard C language used by each person. Container - template class that can accommodate some data. There are versors such as VECTOR, SET, MAP, MULTIMAP and DEQUE in STL. Vector - Basic Array Template, which is a container. Cursor (Iterator) - This is a strange thing, it is a pointer to point to the elements in the STL container, or to other elements. Hello World Program I am willing to write my program in my gold: a Hello World program. This program transmits a string to a character vector and then displays one of the characters in the vector. The vector is like a garden that is growing, and half of all STL containers is based on the vector. If you have the program, you will almost master half the entire STL.
// Program: Vector Demo One // Objective: To understand the vector // #include "stdafx.h" in the STL - If you use the precompiled header file, you contain the header of the header file #include // STL vector file. There is no ".h" here. #include // contains the header file of the COUT object. Using namespace std; // guarantees that members in the STD namespace can be used in the program. Char * szhw = "Hello World"; // This is an array of characters and ends with "/ 0". INT main (int Argc, char * argv []) {Vector vec; // Declare a character vector VECTOR (Array in STL) / / Define a cursor Iterator for a character array. Vector :: item vector vi; // initialize the character, loop the entire string, // is used to fill the data into the character vector until the end of "/ 0". Char * cptr = szhw; // points a pointer to "Hello World" string while (* cptr! = '/ 0') {vec.push_back (* cptr); CPTR ;} // push_back function put data in vector The tail. // Display the characters in the vector in the console for (vi = vec.begin (); vi! = Vec.end (); vi ) // This is the standardized start of the STL loop - usually " ! = ", Not" <"// because" <"is not defined in some containers. // begin () Returns the cursor of the vector starting element (Ite () returns the cursor (Iterator) of the vectors of the vector. {Cout << * vi;} // Use operator "*" to extract data from the cursor pointer. COUT << Endl; // Retine Return 0;} Push_back is the standard function that places the data into the vector or DEQUE (two-end queue). INSERT is a similar function, however it can be used in all containers, but usage is more complicated. End () is actually taking the end of the end (the previous elements at the end of the container) so that the loop is correctly run - it returns the pointer to the most close-to-array boundary. Just like an array in a normal cycle, such as for (i = 0; i <6; i ) {ar [i] = i;} --ar [6] does not exist, this element does not reach this element in the loop. Therefore, there will be no problem in the cycle. One of the troubles of STL - initializing STL's troubles are when it is initialized. The initialization of the containers in the STL is more troublesome than that of the C / C array. You can only be an element, or first initialize a normal array and then fill in the container by transformation. I think people can usually do this: // Program: Initialization Demo // Objective: To illustrate how the vector in STL is initialized.
#include // and The same #include using namespace std; int Ar [10] = {12, 45, 234, 64, 12, 35, 63, 23, 12 , 55}; char * str = "Hello World"; int Main (int Argc, char * argv []) {Vector VEC1 (Ar, Ar 10); Vector Vec2 (STR, STR STRLEN (STR)); RETURN 0;} There are many ways to complete the same work in programming. Another way to fill the fill vector is to use more familiar square brackets, such as the following programs: // Program: Vector Demo 2 // Purpose: To understand the STL vector with array subscript and square brackets #include #include #include Using Namespace std; char * szhw = "Hello World"; int main (int Argc, char * argv []) {Vector vec (strlen); // is vector Distribute memory space INT I, K = 0; char * cptr = SZHW; while (* cptr! = '/ 0') {vec [k] = * cptr; CPTR ; k ;} for (i = 0; i
In addition, you can add Using Namespace STD to any domain, such as the head or a control cycler of the function. Some suggestions To avoid annoying warnings in debug mode, using the following compiler command: #pragma Warning (Disable: 4786) Another thing to note is that you must ensure that between two angle brackets or sharp brackets And the name is spaced between space because it is to avoid confusion with the ">>" shift operator. For example, vector >; this will write error, and this will be written: vector > VECLIS; STL Practice Guidelines (in) STL Practice Guidelines Practical Guide to STL Author: Jeff Bogan another vessel - the set (set) which is Microsoft's help documentation to explain the collection (set): "The description of a control variable-length sequences of elements Object (Note: Key and Value in Sets are key types, and key and value in Map are template classes of two components in a PAIR structure), each element contains a sort key and A value (Value). Any element in the sequence can be found in the sequence, and the time to complete these operations is a ratio of the number of elements in this sequence, and when the binder is deleted When the element is used, the deletion operation is invalid. "And a corrected and more actual definition should be: A collection (SET) is a container, which is unique in it. This is useful when collecting a specific value of a data. The elements in the collection are arranged in a certain order and are used as an example in the collection. If you need a key / value pair (PAIR) to store data, MAP is a better choice. A collection is organized through a linked list, which is slower than the vector (Vector), but finds or adds the end of the elements.
Here is an example: // Program: SET Demo // Purpose: Understand the collection in STL #include #include #include using namespace std; int main (int Argc, char * Argv []) {set StRSET; SET :: Iterator Si; StRSET.INSERT ("Cantaloupes"); strset.insert ("apple"); strset.insert ("Orange"); strset.insert ("banana"); strset.insert ("grapes"); strset.insert ("grapes"); for (Si = strSet.begin (); Si! = strset.end (); Si ) {cout << * Si << ";} cout << Endl; Return 0;} // Out: Apple Banana Cantaloupes grapes Orange // Note: The elements in the output are arranged in the order of alphabetically, and each value is not repeated. . If you are interested, you can replace the output loop with the following code: Copy (strSet.begin (), strset.end (), ostream_iterator (cout, ")) ;. Collection (SET) although more Powerful, but I personally think it is a little unclear and it is easier to make mistakes. If you understand this, you will know what to do with a collection (SET). All STL container containers' concept appeared earlier than template, which was originally an important concept in a computer science area, but here, its concepts were mixed together. Below is the 7 containers that appear in STL: Vector - STL is secure array. Can only add data in the "front" of the Vector. DEQUE (Double-end queue double-ended queue) - is similar to the vector, but data can be added to the front and rear ends. List (list) - The cursor can only be moved at a time. If you are already familiar with the list, then the LIST in the STL is a two-way linked list (each node has two pointers that are forwarded and pointing to the successive subsequent). Set (Collection) - contains sorted data, which must be unique. Map (mapping) -Rolded binary groups, each element in MAP consists of two values, where the key (key value, key value in a map must be unique) Use when sorting or searching, it can be re-acquired in the container; and the other value is the value associated with the element. For example, in addition to the AR [43] = "Overripe" finds a data, the MAP can also find a data via Ar [Banana "] =" Overripe ".
If you want to get the element information, you can easily implement the full name of the input element. MultiSet - and Collection (SET) are similar, but the values are not required to be unique (ie, repetition). MultiMap - and Mapp (MAP) are similar, however, the key value is not required (that is, you can have repetition). Note: If you read Microsoft's help documentation, you will encounter a statement on the efficiency of each container. For example: LOG (N * n) insertion time. The impact of these times can be ignored unless you have to handle a lot of data. If you find that your program has obvious hysteresis or requires time critical things, you can learn more about various container operational efficiency. How to use classes in a map? MAP is a template class that gets value (value) through the Key. Another problem is that you want to use your own classes in Map, not existing data types, such as INT that has been used now. Create a "Template-Ready" class, you must ensure that some member functions and overload operators are included in this class. Some members of the following are required: the default constructor (usually empty) copy constructor overload "=" operator you should overload as many operators as many operators to meet the needs of a specific template, such as if you Want to define a class as a key (key) in the MAP, you must overload the relevant operator. But there is no discussion of overload operators here. // Program: Map the custom class. // Objective: Describe how to use custom classes in MAP.
#include #include #include #include
Normally, the type of ITATOR can vary, so that the container will also have several different ways: Iterator - For any other container other than the Vector, you can use this cursor in a container in a container Take a step in the direction of the front. This means that you can only use the " " operator for this kind of cursor. And you can't use the "-" or " =" operator. For the container of Vector, you can use " =", "-", " ", "=", and "<", "<=", ">", Comparison operators such as "> =", "==", "! =". Reverse_iterator - If you want to use the coming direction instead of the forward direction, you can traverse the elements in the container outside the vector, you can use the reverse_iterator to reverse the direction of traversal, you can also use rbegin () Instead of begin (), replace end (), while the " " operator is traversed in the direction behind. Const_iterator - a cursor in forward direction that returns a constant value. You can use this type of cursor to point to a read-only value. Const_reverse_iterator - a cursor traversed in the opposite direction that returns a constant value. Sort in Set and Map In addition to type and value, templates contain other parameters. You can pass a callback function (usually the statement "predicate" - this is a function with a parameter returns a Boolean value). For example, if you want to automatically create a collection, the elements in the collection are arranged in ascending order, you can create a set class with a concise approach: set > set1greater is another template function (model function), When the value is placed in the container, it is used to sort these values. If you want to arrange these values in descending order, you can write: set > SET1 When implementing the algorithm, the statement is passed as a parameter into a STL template class. Other situations, these situations will be described in detail below. STL's troubles - Error Messages These templates need to be expanded to the compiler, so when the compiler fails for some reason, it will list a long error message, and these error messages are difficult to understand . I don't think there is a good way to deal with this problem. But the best way is to find and carefully study the end of the code segment. Another trouble is: When you double-click the error message, it will correct the internal code of the template library, and these code is more difficult to read. Under normal circumstances, the best way to correct the correctment is to re-check your code and ignore all warning messages when running. Algorithms algorithm is a function used in templates. This really begins to reflect the power of STL. You can learn some of the algorithms that can be used in most template containers so you can sort, find, exchange, etc. in the easiest way. The STL contains a series of functions of a series of implementation algorithms. For example: sort (vec.begin () 1, vec.end () - 1) enables the ordering operation of other elements of the first and last elements. The container itself cannot use an algorithm, but the cursor in the two containers can define an element using algorithm in the container. In this case, the algorithm is not directly limited by the container, but by using a cursor, the algorithm can be supported.
In addition, many times you will encounter a function that is ready (previously mentioned: Predicate) as a parameter, you can also pass the previous old value. The following example demonstrates how to use algorithms: // Program: Test Score Statistics // Objective: How to use algorithm #include // through the operation of the score saved in the vector, you must include the algorithm function, you must include This header file. #include // Contains the header file of the Accumulate function #include #include using namespace std; int testscore [] = {67, 56, 24, 78, 99, 87, 56 }; // Judging whether a grade passes the test bool passed_test (} // judge whether a grade does not have a BOOL FAILED_TEST (INT N) {Return (n <60);} INT Main (int ) {int total; // Initialization vector, enable it to load the elements in the TestScore array Vector Vectestscore (Testscore, Testscore Sizeof (Testscore) / Sizeof (int) ); Vector :: Iterator vi; // Sort and display data in vector sort (vectestscore.begin (), vectestscore.end ()); cout << "sorted test score: << endl; for Vi = vectestscore.begin (); vi! = vectestscore.end (); vi ) {cout << * vi << ",;} cout << Endl; // Display Statistics // min_element returns a _iterator_ type Object, the object points the minimum value of the value. // "*" operator extracts the value in the element. Vi = min_egin (), vectestscore.eGin (); cout << "The lowest score was" << * vi << "." << endl; // is similar, max_element is the largest value. Vi = max_element (vectestscore.egin (), vectestscore.end ()); cout << "The higherst score was" << * vi << "." << endl; // use a declaration function (Predicate function, referring to VECTESTSCORE .begin () and vectestscore.end ()) to determine the number of people through the exam.
Cout << count_ifin (), vectestscore.egin (), passed_test) << "out of" << vectestscore.size () << "students passed the test" << Endl; // Determine how many people The exam hung (VECTESTSCORE.BEGIN (), vectestscore.egin (), filed_test) << "out of" << vectestscore.size () << "" students failed the test "<<" e; 计算 计算 <<< The sum of grades total = Accum (), vectestscore.egin (), vectestscore.egin (), 0); // calculates the average grade COUT << "Average Score WAS" << (Total / (int) () << Endl; Return 0;} Allocator ALLOCATOR is used in the initialization phase of the template, which is a template class that assigns memory space and release space operations for objects and arrays. It plays a very mysterious role in a variety of situations, which is concerned about the optimization of high-level memory, and for black box testing, using allocator is the best choice. Typically, we don't need to specify it because they are usually arguable as the default parameters that do not have to be added. If Allocator appears in a professional test, you'd better understand what it is. Embed Templates and Derive Templates Whenever you use an ordinary class, you can use a STL class in it. It can be embedded: class cParam {string name; string unit; vector vecdata;}; or use it as a base class: Class CParam: public vector {string name; string unit;}; STL The template class needs to be cautious as the base class. This requires you to adapt to this programming. The template in the template is to build a complex data structure, you can implant one template into another template (ie "template nested"). The general method is to define a template type using the TypeDef keyword in front of the program. // Program: Demo in the vector in vector. // Objective: To explain how to use nested STL containers.
#include #include using namespace std; typef vector vec_int; int INP [2] [2] = {{1, 1}, {2, 0}}; // To put into template 2x2 regular array int Main (int Argc, char * argv []) {INT I, J; Vector vecvec; // If you want to implement such nested in a sentence, you can write: / / Vector > vecvec; // fill in the array into vector VEC_INT V0 (INP [0], INP [0] 2); // Pass two pointers // copy the value in the array into the vector VEC_INT V1 (INP [1], INP [1] 2); VECVEC.PUSH_BACK (V0); VECVEC.PUSH_BACK (V1); for (i = 0; i <2; i ) {for (j = 0; J <2; j ) {cout << Vecvec [i] [j] << ";} cout << endl;} return 0;} // output: // 1 1 // 2 0 Although it is very troublesome during initialization Once you bring the data to the vector, you have realized a long expandable two-dimensional array (size can be expanded until the memory is used). Depending on the actual needs, nested combinations of various containers can be used. Summary STL is useful, but difficulties and trouble during use are inevitable. Just like the Chinese said: "If you have a tiger, it is like a tiger." Since the 9CBS article editor may filter out the "<" and ">" part of the "<>" as the HTML tag, it is existing correctly The "Test Fractal Statistics" program is as follows: // Program: Test Score Statistics // Objective: How to use algorithm #include // through the operation of the score saved in the vector, if you want to use an algorithm function, you have to include This header file.
#include // Contains the header file of the Accumulate function #include #include using namespace std; int testscore [] = {67, 56, 24, 78, 99, 87, 56 }; // Judging whether a grade passes the test bool passed_test (} // judge whether a grade does not have a BOOL FAILED_TEST (INT N) {Return (n <60);} INT Main (int ) {int total; // Initialization vector, enable it to load the elements in the TestScore array Vector Vectestscore (Testscore, Testscore Sizeof (Testscore) / Sizeof (int) ); Vector :: Iterator vi; // Sort and display data in vector sort (vectestscore.begin (), vectestscore.end ()); cout << "sorted test score: << endl; for Vi = vectestscore.begin (); vi! = vectestscore.end (); vi ) {cout << * vi << ",;} cout << Endl; // Display Statistics // min_element returns a _iterator_ type Object, the object points the minimum value of the value. // "*" operator extracts the value in the element. Vi = min_egin (), vectestscore.eGin (); cout << "The lowest score was" << * vi << "." << endl; // is similar, max_element is the largest value. Vi = max_element (vectestscore.egin (), vectestscore.end ()); cout << "The higherst score was" << * vi << "." << endl; // use a declaration function (Predicate function, referring to VECTESTSCORE .begin () and vectestscore.end ()) to determine the number of people through the exam.