"C + + Primer Plus" 16.3 Standard Template Library Learning notes

Source: Internet
Author: User

STL provides a set of templates that represent containers, iterate over them, function objects, and algorithms. A container is a cell that is similar to an array and can store several values. STL containers are homogeneous, that is, the type of stored values is the same; an algorithm is a prescription for accomplishing a particular task (such as sorting an array or finding a particular value in a list), iterating over the objects that it can use to traverse the container, similar to a pointer that can facilitate an array, is a generalized pointer; You can make a class object or a function pointer (including the function name, because it is used as a pointer). STL makes it possible to construct various containers (including arrays, queues, and linked lists) and perform various operations (including searching, sorting, and random permutations).
Alex Stepanov and Meng Lee developed the STL in the Hewlett-Packard Lab and released its implementation in 1994. Iso/ansi the C + + committee voted to make it part of the C + + standard. STL does not know object-oriented programming, but a different programming mode-generic programming (generic programming).

16.3.1 template class Vector
In calculations, vectors correspond to arrays, not vectors in mathematics.
The vector class provides operations similar to those described in chapter 14th, Valarray and ARRAYTP, and 4th, to create a vector object, assign a vector object to another object, and use the [] operator to access the vector element. To make a class generic, you should design it as a template class, which is what STL does--a vector template is defined in the head file vector (formerly Vector.h).
To create a vector template object, you can use the usual <type> notation capable to indicate the type to use. In addition, vector templates use dynamic memory allocations, so you can use initialization to indicate how many vectors are required:
#include <vector>
using namespace Std;
Vector<int> ratings (5); A vector of 5 ints
int n;
CIN >> N;
Vector<double> scores (n); A vector of N doubles
Since the operator [] is overloaded, after you create a vector object, you can use the usual array notation to access the individual elements:
Ratings[0] = 9;
for (int i = 0; i < n; i + +)
cout << scores[i] << Endl;

/*-----------------------Dispenser---------------------
Similar to the String class, the various STL concurrent templates accept an optional template parameter that specifies which allocator object to use to manage memory. For example, the beginning of a vector template is similar to the following:
Template <class T, class Allocator = allocator<t> >
Class Vector {...
If you omit the value of the template parameter, the container template will use the Allocator<t> class by default. This class uses new and delete.
--------------------------------------------------*/

16.3.2 operations that can be performed on vectors
All STL containers provide some basic methods, including:
Size ()--Returns the number of elements in the container
Swap ()--the content of the volume cut
Begin ()--Returns an iterator that points to the first element in a container
End ()--Returns an iterator representing the end of the container
Iterator: is a generalized pointer. In fact, it can be a pointer, or it can be an object that can perform a pointer-like operation-such as dereferencing (such as operator* ()) and incrementing (such as operator++ ()). By generalized the pointers to iterate over them, STL is able to provide a uniform interface for a variety of different container classes, including those that cannot be handled by simple pointers. Each container class defines an appropriate iterator whose type is a typedef named iterator, whose scope is the entire class. For example, to declare an iteration for the vector's double type specification, you can do this:
Vector<double>::iterator PD; PD an iterator
Suppose scores is a Vector<double> object:
Vector<double> scores;
You can use iterations of its PD to do such an operation:
PD = Scores.begin (); Has PD point to the first element
*PD = 22.3; Dereference PD and assign value to first element
++PD; Make PD point to the next element
As you can see, the iterator behaves like a pointer.
There is also a useful place for c++11 automatic type inference. For example, you might not do this:
Vector<double>::iterator PD = Scores.begin ();
and doing so:
Auto PD = Scores.begin (); C++11 Automatic type deduction
The over end (Past-the-end) is an iterator that points to which element after the last element of the container. This is similar to the empty string following the last character of the C-style string, which indicates that the null character is a value, and that "over end" is a pointer to an element (an iterator). The end () member function identifies a position that exceeds the end. If the iteration is set to the first element of the container and is incremented continuously, it eventually drops to the end of the large container, thus traversing the contents of the container as a whole. Therefore, if the definition of scores and PD is the same as in the previous example, you can use the following code to explicitly type the contents of the container:
for (PD = Scores.legin (); PD! = Scores.end (); PD + +)
cout << *pd << Endl;
All containers contain the methods that were discussed earlier. The vector template class also contains some methods that only some STL containers have. Push_back () is a convenient way to add elements to the end of a vector. When doing this, it will be responsible for memory management, increasing the length of the vector so that the dog accommodates new members, which means that you can write code like this:
Vector<double> scores; Create an empty vector
Double temp;
while (CIN >> temp && temp >= 0)
Scores.push_back (temp);
cout << "you entered" << scores.size () << "scores.\n";
The erase () method deletes the elements of a given interval in the vector. It accepts that the brother iterates over its parameters, which define the interval to be deleted. It is important to understand how STL uses two iterations to define intervals. The first iteration points to the beginning of the interval, and the second iteration is at the back of the interval at the end of the division. For example, the following code deletes the first and second elements, that is, the element that the begin () and begin () +1 point to (since the vector provides random access, the vector class iterates through operations such as Begin () +2):
Scores.erase (Scores.begin (), Scores.begin () + 2);
If It1 and It2 are iterators, the STL document uses [P1,P2] to represent the intervals P1 to P2 (excluding P2).
The Insert () method has the opposite function as erase (). It takes 3 iterations of its arguments, the first parameter defines the insertion position of the new element, and the second and third iterations whose parameters define the inserted interval, which is usually part of another container object. For example, the following code inserts all elements except the first element in Vector New_v before the first element of the Old_v vector:
Vector<int> Old_v;
Vector<int> New_v;
...
Old_v.insert (Old_v.begin (), New_v.begin () + 1, new_v.end ());
By the way, it's very handy to have a super-tiny element for this situation, because it makes attaching elements at the end of the vector very simple. The following code inserts a new element in front of the Old.end (), which is after the last element of the vector.
Old_v.insert (Old_v.end (), New_v.begin () + 1, new_v.end ());

16.3.3 Other operations that can be performed on vectors
Programmers often want to point to many operations, such as searching, sorting, random sorting, and so on. Does the vector template class contain methods to perform these common operations? The answer is NO! STL defines non-member (Non-member) functions from a broader perspective to perform these operations, that is, instead of defining the find () member function for each container, it defines a non-member function for all container classes, find (). This design concept eliminates a lot of repetitive work. For example, suppose you have 8 container classes and need to support operations in 10. If each class has its own member function, you need to define a 80 (8*10) member function. However, when using STL, you only need to define 10 non-member functions. When defining a new container class, it can also use the 10 non-member functions already in place to perform operations such as finding, sorting, as long as the correct guideline is followed.
On the other hand, even if there are non-member functions that perform the same task, the STL sometimes defines a member function. Because the efficiency of the class-specific algorithm is higher than the general-purpose algorithm for some operations, the Ector member function swap () is more efficient than the non-member function swap (), but the non-member function allows you to exchange the contents of two different types of containers.
Let's look at 3 representative STL functions: For_each (), Random_shuffle (), and sort (). The For_each () function can be used with many container classes, which accept 3 parameters. The first two are iterations that define the interval in the container, and the last is a pointer to the function (more generally, the last parameter is a function object, and the function object will be described later). The For_each () function applies the pointed function to individual elements in the container interval. The function being pointed to cannot modify the value of the container element. You can use the For_each () function instead of a for loop. For example, you can add code:
Vector<review>::iterator PR;
for (pr = Books.begin (); PR! = Books.end (); PR + +)
Showreview (*PR);
To be replaced by:
For_each (Books.begin (), Books.end (), Showreview);
This avoids explicitly invoking iterations of its variables.
The Random_suhffle () function accepts two iterations of the specified interval and randomly arranges the elements in that interval. For example, the following statement randomly arranges all the elements in the books vector:
Random_shuffle (Books,begin (), Books.end ());
Unlike For_each, which can be used with any container class, this function requires that the container class allow random access, which the vector class can do.
The sort () function also requires that the container support random access. The function has two versions, the first version accepts two iterations of its parameters, and operates on the elements in the interval using the < operator defined for the type element stored in the container. For example, the following statement sorts the contents of Coolstuff in ascending order, using the built-in < operator pair to compare only:
Vector<int> Coolstuff;
...
Sort (Coolstuff.begin (), Coolstuff.end ());
If the container element is a user-defined object, to use sort (), you must define a operator< () function that can handle the object of that type. For example, if you provide a member or a non-member function operator< () for review, you can sort the vectors that contain the review object. Since review is a struct, its members are common, and such non-member functions will be:
BOOL operator< (const Review & R1, const Review & R2)
{
if (R1.title < R2.title)
return true;
else if (R1.title = = R2.title && r1.rating < r2.rating)
return true;
Else
return false;
}
With such a function, you can sort the vectors that contain review objects, such as books:
Sort (Books.begin (), Books.end ());
The operator< () function of the previous version is sorted by title of the caption member. If the title member is the same, sort by rating. However, what if you want to sort by descending or by rating (not title)? You can use the sort () in another format. It accepts 3 parameters, the first two parameters are also iterations of the specified interval, and the last parameter is a pointer to the function to be used (the function object), not the operator< () used for comparison. The return value can be converted to Bool,false to indicate that the order of two parameters is incorrect. Here is an example:
BOOL Worsethan (cosnt Review & R1, const Review & R2)
{
if (R1.rating < r2.rating)
return true;
Else
return false;
}
With this function, you can use the following statement to sort the books vectors containing the review objects in ascending order:
Sort (Books.begin (), Books.end (), Worsethan);

16.3.4 Range-based for loop (C++11)
The 5th chapter says that the range-based for loop is designed for use with STL. To review the cycle, here is the first example of the 5th chapter:
Double Prices[5] = {4.99, 10.99, 6.87, 7.99, 8.49};
for (double x:prices)
cout << x << Std::endl;
In this for loop, the code inside the parentheses declares a variable of the same type as the container's stored content, and then indicates the name of the container. Next, the loop body accesses each element at the same time using the specified variable. For example, for the following statement from listing 16.9 of the program:
For_each (Books.begin (), Books.end (), Showreview);
You can replace it with the following range-based for loop:
for (auto X:books) Showreview (x);
Depending on the type of book (vector<review>), the compiler infers that the type of x is Review, and the loop will pass each Review object in books once to Showreview ().
Unlike For_each (), a range-based for loop modifies the contents of a container, and the trick is to develop a reference parameter. For example, suppose you have the following function:
void Inflatereview (Review &r) {r.rating++;}
You can use the following loop to execute the function for each element of books:
For (Auto & x:books) Inflatereview (x);

C + + Primer Plus 16.3 Standard Template Library Learning notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.