Author: Jeff Bogan Translation: Zhou Xiang Source: Translator's Note This is a guide you learn how to STL in Microsoft Visual Studio and practice articles. 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 advantages:
It is convenient to easily implement a series of algorithms such as search data or sort of data; more secure and convenient when debugging procedures; even if people use STL, you can easily understand (because STL is cross-platform of). 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
// 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
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 This method is relatively long, but is the best way to mix the use of multiple namespaces. Some STL's fanatics have been using this method and regard those who do not use this method as a heterogeneous. Some people will build some macro simplified issues through this approach. 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 If you are interested, you can replace the output loop with the following code: Copy (strSet.Begin (), strset.end (), ostream_iterator The default constructor (usually empty) copy constructor overload "=" operator you should overload as many operators as possible to meet the needs of a particular template, for example, if you want to define a class as MAP Key (key), 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 Store these values in the container is not a good idea, because every new value is added to the container or has a value deleted from the container, these values will be invalid. To a certain extent, the cursor can be regarded as a handle (HANDLE). 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 method: set Set #include #include #include Using namespace std; INT testscore [] = {67, 56, 24, 78, 99, 87, 56}; // Judgment whether a grade passed the exam bool passed_test (@ = 60);} // Judgment one Whether the score does not have a BOOL FAILED_TEST (INT N) {Return (N <60);} int Main (int Argc, char * argv []) {int total; // initialization vector, enable it to load the element in the Testscore array Vector 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 >; this will write error, and this will be written: vector
> VECLIS; Another container-collection (SET) This is an explanation of a collection (SET) in Microsoft Help document: "Describes an object that controls the sequence of germplasm (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). You can find, insert, and delete sequences for this sequence. Any element in the middle, and the time to complete these operations is a ratio ratio relationship between the number of elements in this sequence, and when the binder points to a deleted element, the delete operation is invalid. "And a corrected and actual The definition should be: A set (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 it is slow to find or add the end of the element. Here is an example: // Program: SET Demo // Purpose: Understand the collection in STL #include