STL introduction, standard template library

zhaozj2021-02-08  223

STL introduction, standard template library

By Scott Field Failure Translation

This article is a new extension of the C language - Standard Template Library, also called STL. When I first intended to write an article about STL, I had to admit that I went to underestimate the depth and breadth of this topic. There are a lot of content to be covered, and there are a lot of books that describe STL. So I re-consider my original idea. Why do I have to write this article, why do you want to contribute? What will this use? Is there any need to come back about STL?

When I opened the Musser and Saini page, I saw the programming era ablation in front of me. I can see that the night has disappeared, and the target software project has appeared. I saw the maintenance code. One year has passed, I use STL written software still easy to maintain. It is a very surprised that others can have a good maintenance!

However, I also remember that it is difficult to understand those technical terms when they start. Once, I bought Musser & Saini, and everything appeared in turn, but there were some good examples who were most eager to get there.

When I started, Stroustrup as part of C has not come yet, it covers STL.

So I would like to write an article about a real life of a STL programmer. If I have some good examples in my hand, especially the new topic like this, I will learn faster.

Another thing is that STL should be very easy to use. Therefore, in theory, we should start using STL immediately.

What is STL? STL is Standard Template Library, standard template library. This may be the most boring term for the most exciting tool in history. Fundamentally, STL is a collection of "containers", these "containers" include List, Vector, SET, MAP, etc., STL is also a collection of algorithms and other components. The collection of "containers" and algorithms here refers to a masterpiece of many smart people in the world.

The purpose of STL is to standardize components so you don't have to revoke them. You can only use these ready-made components. STL is now part of C , so there is no additional installation. It is built within your compiler. Because STL's list is a simple container, I intend to introduce STL how to use it from it. If you know this concept, there is no problem in other things. In addition, the List container is quite simple, we will see this.

In this article we will see how to define and initialize a list, calculate the number of elements, find elements, delete elements, and some other operations from a list. To do this, we will discuss two different algorithms, and the STL general algorithm can operate more than one container, and the member function of the List is a proprietary operation of the LIST container.

This is a simplicity of three primary STL components. The STL container can save objects, built-in objects, and class objects. They safely save objects and define the interface we can operate. Eggs put on the egg rack will not roll to the table. They are safe. Therefore, the objects in the STL container are also very secure. I know this metaphor is very old soil, but it is correct.

The STL algorithm is a standard algorithm that we can apply them on those containers. These algorithms have very famous execution characteristics. They can sort objects, delete them, give them a record, compare, find special objects, merge them into another container, and perform other useful operations.

STL Iterator is like a pointer to the object in the container. The algorithm of STL uses Iterator on the container on the container. Iterator sets the boundary of the algorithm, the length of the container, and some things. For example, some Iterator only allows algorithm reading elements, some let algorithm write elements, and there are some of them. Iterator also determines the direction processed in the container. You can get a Iterator that pointing to a container start position by calling a member function becom () of the container. You can call a container's END () function to get the last value of the past (that is, the value of the value stops).

This is the other thing of STL, the container, algorithm, and the Iterator that allows algorithms to work on the elements in the container. The algorithm operates objects in a suitable, standard approach, and can get the exact length of the container via Iterator. Once these do this, they will not "run out the boundary." There are also other components that have functional enhanced functions of these core components, such as function objects. We will see examples about these, now let's take a look at the List of STL.

Define a list

We can define a STL List like this:

#include

#include

INT main (void) {

List Milkshakes;

}

This is, you have defined a list. Is it simple? List Milkshakes This sentence is that you declare an instance of the list template class, and then an object of instantiation this class. But don't worry about this. In this step in this, you only need to know that you define a string LIST. You need to include the header file that provides the STL List class. I use GCC 2.7.2 to compile this test program on my Linux, for example:

G Test1.cpp -otest1

Note that iostream.h This header file has been given up by the STL's header file. This is why there is no reason in this example.

Now we have a list, we can use it to use it. We will add a string to this list. There is a very important thing called List value type. The value type is the type of object in the List. In this example, this List's value type is a string, string because this list is used to make strings.

I Insert an element into the List using the member function of the list_back and push_front

#include

#include

#

INT main (void) {

List Milkshakes;

Milkshakes.push_back ("chocolate");

Milkshakes.push_back ("strawberry");

Milkshakes.push_front ("limited");

Milkshakes.push_front ("vanilla");

}

We now have a list with four strings in it. The list member function push_back () places an object onto the back of the list. The list member function push_front () puts one on the front. I often push_back () some error messages onto A list, and then push_front () A Title on the list so itprints before the error. We now have 4 strings in LIST. The member function of the List puts an object behind a list, while push_front () puts the object in front. I usually put some error information push_back () into a list, then push_front () a title to list so that it will print it before this error message. THE LIST MEMBER FUNCTION EMPTY () List member function EMPTY ()

It is important to know if a List is empty. If the list is empty, the member function of Empty () is true. I usually use it like this. I use push_back () to put the error message in the list. Then, by calling EMPTY (), I can say that this program reports an error. If I define a list to put information, a warning, a serious error, I can easily say that the type of error occurs easily by using Empty ().

I can organize these LISTs and then use the title to organize them before printing them, or sort them into classes.

This is what I mean:

/ *

|| Using a list to TRACK AND Report Program Messages and Status

* /

#include

#include

#include

#

INT main (void) {

#define ok 0

#define info 1

#define Warning 2

#

Int retURN_CODE;

#

List infMessages;

List <: string> warningmessages;

#

// During a Program these Messages Are Loaded At Various Points

Infomessages.push_back ("info: program start");

// Do Work ...

WARNINGMESSAGES.PUSH_BACK ("Warning: No Customer Records Have Been Found");

// Do Work ...

#

Return_code = OK;

#

IF (! infMessages.empty ()) {// there is info message

Infomessages.push_front ("INFORMATIONAL MESSAGES:");

// ... Print The Info Messages List, WE'LL See How Later

RETURN_CODE = INFO;

}

#

IF (! warningmessages.empty ()) {// there

WARNINGMESSAGES.PUSH_FRONT ("WARNING Messages:"); // ... print the warning message list, we'll see how late

Return_code = warning;

}

#

// if there.............

IF (Infomessages.empty () && WarningMessages.empty ()) {

COUT << "there" there "tre no message" << Endl;

}

#

Return return_code;

}

Use for loop to process elements in LIST

We want to traverse a list, such as printing all objects to see the results of different operations on the list. To traverse a List of an element, we can do this:

/ *

|| How to Print The Contents of a Simple Stl List. Whew!

* /

#include

#include

#include

#

INT main (void) {

List Milkshakes;

List :: item Milkshakeiterator;

#

Milkshakes.push_back ("chocolate");

Milkshakes.push_back ("strawberry");

Milkshakes.push_front ("limited");

Milkshakes.push_front ("vanilla");

#

// print the milkshakes

Milkshakes.push_front ("The Milkshake Menu");

Milkshakes.push_back ("*** Thats the End ***");

Milkshakeiterator = Milkshakes.begin ();

Milkshakeiterator! = Milkshakes.end ();

Milkshakeiterator) {

// dereference the iterator to get the element

Cout << * Milkshakeiterator << Endl;

}

}

This program defines an Iterator, MilkShakeiterator. We point it to the first element of this List. This can call MilkShakes.Begin () to do it, it will return a Iterator pointing to the List. Then we compare it and the return value of Milkshakes.end (). When we arrived there, stopped.

The end () function of the container returns an item of Iterator to the last position of the container. When we arrive there, stop the operation. We cannot ignore the return value of the END () function of the container. We only know that it means that the end of this container has been processed, should stop processing. All STL containers must do this.

In the above example, each time the FOR cycle is executed, we repeatedly refer to Iterator to get our printed string.

In STL programming, we use one or more items in each algorithm. We use them to access objects in the container. To access a given object, let's point to it, then indirectly quote this item.

This List container is like what you think, it does not support a number of objects to point to one number in Iterator. That is, we can't use Milkshakes.Begin () 2 to point to the third object in the list, because the STL's list is implemented with a double-stranded list, which does not support random access. Vector and Deque (vector and dual queues) and some other STL containers can support random access. The above program prints out the contents in the list. Anyone read it, you can figure out how it works. It uses standard Iterator and standard LIST containers. There is not much programmer relying on what it put in it, just standard C . This is an important step. This example uses STL to make our software more standard.

Use STL's general algorithm for_each to handle elements in LIST

Using STL LIST and ITERATOR, we should initialize, compare, and give iterator increments to traverse this container. STL - common for_each algorithms can alleviate our work.

/ *

|| How to Print A Simple STL List Mkii

* /

#include

#include

#include

#include

#

PrintIt (String & StringToprint) {

Cout << StringToprint << endl;

}

#

INT main (void) {

List FruitandVegetables;

FruitandVegetables.push_back ("carrot");

FruitandVegetables.push_back ("pumpkin");

FruitandVegetables.push_back ("Potato");

FruitandVegetables.push_front ("apple");

FruitandVegetables.push_front ("pineapple");

#

FOR_EACH (FruitandVegetables.begin (), FruitandVegetables.end (), PrintIt);

}

In this program we use STL's general algorithm for_each () to traverse a range of Iterator, then call printit () to handle each object. We don't need to initialize, compare and give Iterator increments. FOR_EACH () has completed these work for us. We execute the operation on the object being packed in this function, we don't have to do that loop, our code is clearer.

The FOR_EACH algorithm references the concept of the Iterator range, which is the range pointed out by the starting iterator and one end Iterator. The starting item indicates where the operation is started, the end Iterator indicates where the end, but it is not included in this range.

Statify the number of elements in the List using STL's general algorithm count ().

The general algorithm of STL count () and count_it () are used to record objects in the container. Just like for_each (), count () and count_if () algorithms are also done in the iTerator range.

Let us have a number of people in the LIST of a student test. This is a integer list.

/ *

|| How to count Objects in An Stl List

* /

#include

#include

#

INT main (void) {

List score;

#

Scores.push_back (100); scorers.push_back (80); scores.push_back (45); scorers.push_back (75);

Scores.push_back (99); scores.push_back (100);

#

INT NUMBEROF100SCORES (0);

Count (Scores.Begin (), ScoreS.end (), 100, Numberof100scores);

#

Cout << "there" << numberof100scores << "scorers of 100" << ENDL;

}

The count () algorithm counts the number of objects equal to a certain value. In the above example it checks each integer object in a list against 100. It increments the variable NumberOf100Scores each time a container object equals 100. The output of the program is Count () algorithm statistically equal to the number of objects of a certain value. The above example exams each of the integer objects in the List. Objects in each container is equal to 100, it gives Numberof100Scores plus 1. This is the output of the program:

There Were 2 Scores of 100

Use STL's general algorithm count_if () to count the number of elements in List

Count_if () is a more interesting version of count (). He used STL's new component, function object. Count_if () Belts a parameter of a function object. Function object is a class with at least one Operator () method. Some STL algorithms are used as a parameter to receive function objects and call the Operator () method of this function object.

The function object returns TRUE or FALSE when the STL algorithm calls Operator. They determine this function based on this. It is more clear to give an example. Count_if () makes a more complex assessment than Count () by passing a function object to determine if an object should be recorded. In this example we will sell the number of toothbrush. We will submit sales records containing four characters and product descriptions.

/ *

|| USING A Function Object To Help Count Things

* /

#include

#include

#include

#

Const string toothbrushcode ("0003");

#

Class isatoothbrush {

PUBLIC:

Bool Operator () (String & SalesRecord) {

Return SalesRecord.substr (0,4) == TOTHBRUSHCODE;

}

}

#

INT main (void) {

List SalesRecords;

#

SalesRecords.push_back ("0001 soap");

SalesRecords.push_back ("0002 shampoo");

SalesRecords.push_back ("0003 toothbrush");

SalesRecords.push_back (0004 toothpaste ");

SalesRecords.push_back ("0003 toothbrush");

#

Int Numberoftoothbrushes (0); Count_if (SalesRecords.begin (), SalesRecords.end (),

ISATOTHBRUSH (), NUMBEROTHBRUSHES

#

Cout << "there" "

<< Numberoftoothbrushes

<< "TOTHBRUSHES SOLD" << Endl;

}

This is the output of this program:

There WERE 2 TOTHBRUSHES SOLD (a total of two toothbrushes)

This program works this way: Define a function object class isatoothbrush, which can determine if the sale is a toothbrush. If this record is a record of selling a toothbrush, the function calls Operator () returns a true, otherwise returns false.

The count_if () algorithm handles the container object by the range of first and second two Iterator parameters. It will increase the value of NumberoftOothbrushes to the objects in the container that returns True in TRUE.

The final result is that NumberoftOothbrushes saves the number of records of the product code domain "0003", which is the number of toothbrush.

Note that the third parameter ISATOTHBRUSH () of count_if () is an object that is temporarily constructed by its constructor. You can pass a temporary object of the ISATOTHBRUSH class to a count_if () function. Count_if () will call each object of the container to call this function.

A more complex function object using count_if ().

We can further study the function object. Suppose we need to pass more information to a function object. We can't do this by calling Operator because it must be defined as the type of object in a list. However, we can use any of the information we need to initialize it with any information we need for isatoothbrush. For example, we may need to have an uncertain code for each toothbrush. We can add this information to the functions of the following:

/ *

|| Using A More Complex Function Object

* /

#include

#include

#include

#include

#

Class isatoothbrush {

PUBLIC:

ISATOTHBRUSH (String & IntoothBrushcode):

TOTHBRUSHCODE (INTOTHBRUSHCODE) {}

Bool Operator () (String & SalesRecord) {

Return SalesRecord.substr (0,4) == TOTHBRUSHCODE;

}

Private:

String Toothbrushcode;

}

#

INT main (void) {

List SalesRecords;

#

SalesRecords.push_back ("0001 soap");

SalesRecords.push_back ("0002 shampoo");

SalesRecords.push_back ("0003 toothbrush");

SalesRecords.push_back (0004 toothpaste ");

SalesRecords.push_back ("0003 toothbrush");

#

String VariableToothBrushcode ("0003"); #

Int Numberoftoothbrushes (0);

Count_if (SalesRecords.begin (), SalesRecords.end (),

ISATOTHBRUSH (Variabletoothbrushcode),

Numberoftoothbrushes);

Cout << "there" "

<< Numberoftoothbrushes

<< "TOTHBRUSHES MATCHING CODE"

<< Variabletoothbrushcode

<< "SOLD"

<< ENDL;

}

The output of the program is:

There Were 2 Toothbrushes Matching Code 0003 Sold

This example demonstrates how to pass information to the function object. You can define any constructor you want, you can do anything you want to do again, you can legally compile.

You can see that the function object really expands the basic count algorithm.

So far, we have learned:

Define a list to the list to learn how List is empty how to use for loops to traverse how List uses STL's general algorithm for_each to traverse List List member functions Begin () and end () and their meaning Iterator range concept And a range of last position is actually not dealt with this fact how this is how to use the STL general algorithm count () and count_if () how the object in a list is how to define a function object.

I use these examples to demonstrate the general operation of the List. If you understand these basic principles, you can use STL without doubt that you do some exercises. We now use some more complex operations to expand our knowledge, including List member functions and STL general algorithms.

Use the STL universal algorithm Find () to find objects in LIST

How do we find things in LIST? STL's general algorithm Find () and FIND_IF () can do this. Like for_each (), count (), count_if (), these algorithms also use the Iterator range, which indicates a list or any other container to process. Usually the first Iterator refers to the position of the beginning, and the Iterator pointed to stop processing. The elements pointed out by times Iterator are not processed.

This is Find () work:

/ * || How to find things in an stlist * / #include #include #include # int main (void) {list fruit; list :: Iterator Fruititerator # Fruit.push_back ("apple"); Fruit.push_back ("PineApple"); Fruit.push_Back ("Star Apple"); # fruititerator = find (Fruit.Begin (), Fruit.end (), "PineApple" ); # Ix (fruititerator == fruit.end ()) {cout << "Fruit not found in list" << Endl;} else {cout << * fruititerator << Endl;}} output is:

PineApple

If you don't find the object pointed out, you will return Fruit.end () value. If you find it, return a point to Iterator that pointing to the object.

Search objects in list using STL universal algorithm Find_if ()

This is a more powerful version of Find (). This example demonstrates find_if (), which receives the parameters of a function object as a parameter and uses it to do more complex evaluation objects and give the lookup criteria.

Suppose there are some records containing events and dates in our List. We want to find an event that happened in 1997.

/ *

|| How to find things in an Stl List Mkii

* /

#include

#include

#include

#

Class Eventisin1997 {

PUBLIC:

BOOL Operator () (String & EventRecord) {

// Year Field Is At Position 12 for 4 Characters in EventRecord

Return EventRecord.substr (12, 4) == "1997";

}

}

#

INT main (void) {

List Events;

#

// String positions 0123456789012345678901234567890123456789012345

Events.push_back ("07 January 1995 Draft Plan of House Prepared");

Events.push_back ("07 February 1996 Detailed Plan Of House Prepared");

Events.push_back ("10 January 1997 Client Agrees To Job");

Events.push_back ("15 January 1997 Builder Starts Work On Bedroom");

Events.push_back ("30 April 1997 Builder Finishes Work");

#

List :: item Eventiterator =

Find_if (Events.begin (), Eventisin1997 ()); #

// Find_if Completes the first time eventisin1997 () Returns true

// for any Object. it Returns an iterator to That Object Which WE

// can dereference to get the object, or if Eventisin1997 () () NEVER

// returned true, find_if returns end ()

IF (Eventiterator == Events.end ()) {

Cout << "Event not found in list" << Endl;

}

Else {

Cout << * Eventiterator << Endl;

}

}

This is the output of the program:

10 January 1997 Client Agrees To Job

Use the STL universal algorithm Search to find a sequence in LIST

Some characters are very good in the STL container, let's take a look at a difficult character sequence. We will define a list to place characters.

List characters;

Now we have a character sequence, it does not use any help, you will know and manage the memory. It knows where it starts, where is it ended. It is very useful. I don't know if I said the character array ended with NULL.

Let us join some characters we like to this list:

Characters.push_back ('/ 0'); characters.push_back ('/ 0'); characters.push_back ('1'); characters.push_back ('2');

How many empty characters will we get?

INT Numberofnullcharacters (0);

Count (Characters.Begin (), Characters.end (), '/ 0', Numberofnullcharacters;

COUT << "We Have" << Numberofnullcharacters << Endl;

Let us find characters '1'

List :: iterator it;

Iter = find (characters.begin (), characters.end (), '1');

COUT << "We found" << * iter << endl;

This example demonstrates that the STL container allows you to handle empty characters in a more standard approach. Now let's use STL's Search algorithm to search for two NULLs in the container.

Just like you guess, STL general algorithm search () is used to search for a container, but search for an element string, not like Find () and FIND_IF () Search only for individual elements.

/ *

|| How to use the Search Algorithm in An Stl List

* /

#include

#include

#include

#

INT main (void) {

#

List targetcharacters;

List listofcharacters;

#

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

New Post(0)