STL Practice Guide (below)

zhaozj2021-02-16  59

STL Practice Guidelines Practical Guide to STL Author: Jeff Bogan Translation: Zhou Xiang

(Connected)

Iterator

I said that the cursor is a pointer, but it is not just a pointer. The cursors and pointers are very similar, and the functions are very like pointers, but in fact, the cursor returns a value from the container in the container. 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 build a set class with a concise method:

Set > set1

Greater

It is another template function (norm function) that is used to sort these values ​​when the value is placed in the container. If you want to arrange these values ​​in descending, you can write this:

Set > set1

When implementing an algorithm, a lot of situations are passed as a parameter into a STL template class, and these situations will be described in detail below.

STL's troubles - Error information

Names of these templates need to be expanded to the compiler, so when the compiler fails, 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

The algorithm is a function used in the template. 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 // purpose: How to use algorithm by operating the score saved in the vector

#include

// 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 (int N) {return (n> = 60);

/ / 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 the data in the 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 that points the minimum value of the value. // "*" operator extracts the value in the element. Vi = min_egin (), vectestscore.end ()); cout << "The lowest score was" << * vi << "." << endl;

// Similar to Min_Element, MAX_ELEMENT is the maximum 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_if (vectestscore.begin (), vectestscore.end (), passed_test) << "out of" << vectestscore.size () << "students passed the test" << Endl;

/ / Determine how many people exam hung COUT << count_if (vectestscore.begin (), vectestscore.end (), failed_test) << "out of" << vectestscore.size () "students failed the test"

// Calculate the sum of grades Total = Accum (), vectestscore.egin (), vectestscore.egin (), 0); // calculate the average grade COUT << "Average Score WAS" << (Total / (INT) (vectestscore.size ())) << ENDL;

Return 0;}

ALLOCATOR (Distributor)

Allocator is used in the initial 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 {Stringn; String unit;

The STL template class needs to be cautious as the base class. This requires you to adapt to this programming.

Template in the template

To build a complex data structure, you can implant a 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;

Typedef vector vec_int;

INT INP [2] [2] = {{1, 1}, {2, 0}}; // To put the regular array of 2x2 in the template

INT Main (int Argc, char * argv []) {Int i, j; vector vecvec; // If you want to implement such nested in one sentence, you can write: // Vector > vecvec; // Fill in the array in vector VEC_INT V0 (INP [0], INP [0] 2); // Pass two pointers // copy the values ​​in the array to 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 troublesome when initialization, once you bring the data, you will have 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 master it, it is like a tiger to add."

Related Links: Josuttis Website: http://www.josuttis.com/pretty Good Initialization Library: http://www.codeproject.com/vcpp/stl/pgil.asp

(Full text)

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

New Post(0)