STL Practice Guide (1)

Source: Internet
Author: User

STL Practice Guide Practical Guide to STL
Translated by Jeff bogan: Zhou Xiang

Translator's note
This article describes how to learn STL and practice it in Microsoft Visual Studio. This article begins with the basic knowledge of STL, step by step

Step by step, it involves STL coding methods, compiling and debugging of STL code, namespace, and ANSI/ISO strings in STL.

Various types of containers, templates, cursors, algorithms, and Splitters

(Allocator), nesting of containers, etc. In this article, the author puts forward some suggestions for readers and points out the questions that should be paid attention to when using STL.

Question. This article has a wide coverage and comprehensive perspectives. It is not only suitable for beginners to learn STL, but also a practical guide for readers to use STL programming.

STL Introduction

STL (Standard Template Library) is a good technology that everyone engaged in C ++ programming needs to master. I think every

It may take some time for beginners to familiarize themselves with STL. For example, when learning STL, there will be a steep learning curve, and some names are not intuitive.

It can be remembered (maybe a good name has been used up), but once you master STL, you will not feel a headache. Compared with MFC, STL is more

Complex and powerful.
STL has the following advantages:

It is easy to implement a series of algorithms such as searching data or sorting data;

It is safer and more convenient to debug programs;

Even the codes written by people using STL on UNIX platforms can be easily understood (because STL is cross-platform ).

Background

Writing this part makes some beginners have a good start in the challenging computer science field, without having to understand the endless

Here, we only use these terms and rules as the product stler used for self-entertainment.

Use Code
The code used in this article is of guiding significance in STL practice.

Definition of some basic concepts

Template: Macro of A Class (and various data types and functions such as structures ). Sometimes called cookie cutter ),

The formal name should be called the model (generic) -- A class template is called the model class (generic class), and a function template is naturally

It is called a generic function ).
STL-a standard template library, some templates written by smart people, has now become part of the standard C ++ language used by everyone.
Container-a template class that can hold some data. STL contains containers such as vector, set, MAP, multimap, and deque.
Vector-a basic array template, which is a container.
Cursor (iterator) -- this is a strange thing. It is a pointer that points to elements in the STL container and can also point to other elements.

Hello World Program

I would like to write my program: A Hello World Program in my prime time. This program transfers a string to a character vector, and then

One character in the vector is displayed each time. A vector is like a garden that holds variable-length arrays. About half of all STL containers are vector-based.

Program, you have almost mastered half of the whole STL.

// Program: vector demonstration 1
// Objective: To understand the vectors in STL

// # Include "stdafx. H"-if you use a precompiled header file, this header file is included.
# Include <vector> // header file of the STL vector. There is no ". H" here ".
# Include <iostream> // header file containing the cout object.
Using namespace STD; // ensure that Members in the STD namespace can be used in the program.

Char * szhw = "Hello World ";
// This is a character array ending with "/0.

Int main (INT argc, char * argv [])
{
Vector <char> VEC; // declare a Character Vector vector (array in STL)

// Define a cursor iterator for the character array.
Vector <char>: iterator VI;

// Initialize the Character Vector to loop the entire string,
// Fill in the data in the Character Vector until it ends when "/0" is encountered.
Char * cptr = szhw; // point a pointer to the "Hello World" String
While (* cptr! = '/0 ')
{Vec. push_back (* cptr); cptr ++ ;}
// The push_back function places the data at the end of the vector.

// Display characters in the vector one by one on the console
For (Vi = Vec. Begin (); vi! = Vec. End (); vi ++)
// This is the beginning of STL loop normalization-usually "! = ", Not" <"
// Because "<" is not defined in some containers.
// Begin () returns the cursor (iterator) of the starting element of the vector, and end () returns the cursor (iterator) of the element at the end of the vector ).
{Cout <* VI;} // use the "*" operator to extract data from the cursor.
Cout <Endl; // line feed

Return 0;
}

Push_back is a standard function that puts data into a vector (vector) or deque (double-end Queue. Insert is a similar function, but it

Can be used in containers, but the usage is more complex. End () is actually adding one at the end (taking the previous element at the end of the container) to make the loop run correctly.

-- It returns the pointer to the data closest to the array limit. Just like an array in a normal loop, such as for (I = 0; I <6; I ++) {ar [I] = I ;}--

Ar [6] does not exist. It does not reach this element in the loop, so there will be no problems in the loop.

One of STL's troubles-initialization

STL is annoying when it is initialized. The initialization of containers in STL is much more troublesome than the initialization of arrays in C/C ++. You can only have one element and one element

Or initialize a common array and put it in the container by converting it. I think people can do this:

// Program: initialization demo
// Purpose: to demonstrate how vectors are initialized in STL.

# Include <cstring> // <cstring> is the same as <string. h>.
# Include <vector>
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 <int> vec1 (AR, Ar + 10 );
Vector <char> vec2 (STR, STR + strlen (STR ));
Return 0;
}

 

There are many ways to accomplish the same job in programming. Another method of filling a vector is to use square brackets that are more familiar with, such as the following program:

// Program: vector demonstration 2
// Objective: to understand STL vectors with array subscript and square brackets

# Include <cstring>
# Include <vector>
# Include <iostream>
Using namespace STD;

Char * szhw = "Hello World ";
Int main (INT argc, char * argv [])
{
Vector <char> VEC (strlen (SHW); // allocates memory space for the Vector
Int I, K = 0;
Char * cptr = szhw;
While (* cptr! = '/0 ')
{VEC [k] = * cptr; cptr ++; k ++ ;}
For (I = 0; I <Vec. Size (); I ++)
{Cout <VEC [I];}
Cout <Endl;
Return 0;
}

This example is clearer, but there are fewer operations on the cursor (iterator), and an additional integer number is defined as the subscript. In addition, you must clearly

Specify the memory space allocated to the vector.

Namespace)

The concept related to STL is namespace ). STL is defined in the STD namespace. There are three methods to declare the namespace used:

1. Use this namespace with the Using Keyword, at the top of the file, but add it under the declared header file:
Using namespace STD;
This is the simplest and best method for a single project. This method can limit your code to the STD namespace.

2. Declare (like prototype) each object to be used before using each template ):
Using STD: cout;
Using STD: Endl;
Using STD: flush;
Using STD: Set;
Using STD: inserter;
Although this is a bit lengthy, it can be advantageous for the functions used by memory, and you can easily declare and use members in other namespaces.

3. Use the STD domain identifier every time you use a template in the STD namespace. For example:
Typedef STD: vector vec_str;
Although this method is lengthy to write, it is the best way to mix multiple namespaces. Some STL enthusiasts always use this method, and

Consider people who do not use this method as different. Some people will use this method to create some macros to simplify the problem.

In addition, you can add using namespace STD to any domain. For example, you can add it to the function header or a control loop body.

Some Suggestions

To avoid annoying warnings in debug mode, run the following compiler command:

# Pragma warning (Disable: 4786)

Another thing to note is that you must ensure that the two angle brackets are separated by spaces or between the angle brackets and their names, because they are used to avoid shift operations similar to "> ".

Character obfuscation. For example
Vector <list <int> veclis;
In this case, an error is reported, while in this case:
Vector <list <int> veclis;
You can avoid errors.

(To be continued)

 

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.