STL Practice Guide (I)

Source: Internet
Author: User
Tags integer numbers

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 starts from the basic knowledge of STL, and is step-by-step and step-by-step. It involves STL coding methods, compiling and debugging of STL code, and namespace) ANSI/ISO string in STL, various types of containers (container), template, cursor (iterator), algorithm (algorithms), and allocator) in this article, the author puts forward some suggestions for readers and points out the issues that should be paid attention to when using STL. 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 beginner of STL should spend some time getting familiar with it. For example, when learning STL, there will be a steep learning curve, in addition, some naming rules are not easy to remember by intuition (maybe a good name has been used up). However, 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 is a good start for some beginners of computer science in the challenging field of computer science, without having to learn the endless terms and dull rules, here, we only use those things and rules as the creative products stler uses for their own entertainment.

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

Definition of some basic concepts

Template )--Class (as well as the structure of various data types and functions) macro (macro ). Sometimes it is called cookie cutter. The regular name should be called Generic. The template of a class is called generic class ), A function template is naturally called a general 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 )--Basic array template, which is a container.
Cursor (iterator )--This is a strange thing. It is a pointer used to point to elements in STL containers, or 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 displays a character in the vector each time. Vector is like a garden where variable-length arrays are stored. About half of all STL containers are vector-based. If you have mastered this 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 all containers, but its 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-the pointer it returns points to the data closest to the array boundary. Just like an array in a normal loop, for example, for (I = 0; I <6; I ++) {ar [I] = I ;}-- ar [6] does not exist, this element is not reached 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 use one element or one element, or initialize a common array before entering it into the container through conversion. 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 additional integer numbers are defined as subscripts, you must clearly explain in the program How much memory space is 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 <: String> vec_str;
Although this method is lengthy to write, it is the best way to mix multiple namespaces. Some STL enthusiasts keep using this method, and treat people who do not use this method as a different type. 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)

Note that you must separate the angle brackets or the names with spaces to avoid confusion with the ">" shift operator. 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.