STL provides three basic containers: vector, list, And deque.

Source: Internet
Author: User

VectorSimilar to the built-in array,It has a continuous memory and the starting address remains unchanged.Therefore, it supports random access, that is, the [] Operator. However, because its memory space is continuous, inserting and deleting in the middle will cause the copy of memory blocks, in addition, when the memory space after the array is insufficient, you need to apply for a memory that is sufficiently large and copy the memory. These greatly affect the efficiency of vector.

 ListIt is a two-way linked list in the data structure (based on the sgi stl source code). Therefore, its memory space can be discontinuous and data access can be performed through pointers, this feature makes random access very inefficient, so it does not provide a [] OPERATOR overload. However, due to the characteristics of the linked list, it supports deletion and insertion anywhere with good efficiency.

Deque is a double-ended queue. Its implementation is not clear, but it has the followingTwo features: It supports [] operators, that is, instant access, and is less efficient than vector. It supports operations at both ends: push_back, push_front, pop_back, pop_front, etc, in addition, the operation efficiency on both ends is similar to that on list.

Therefore, in actual use, how to select one of the three containers should be determined according to your needs. Generally, the following principles should be followed:
1. If you need efficient instant access without worrying about the efficiency of insertion and deletion, use the Vector
2. If you need to insert and delete a large number of objects without having to access them immediately, you should use list
3. If you need immediate access and care about data insertion and deletion at both ends, use deque.

 

STL is part of the ANSI/ISO standard for C ++ and can be used in all c ++ language compilers and all platforms. The same version of STL is available in any hardware configuration. STL provides a large number of reusable software organizations. For example, programmers no longer need to design their own sorting and search algorithms. These are already part of STL. The code written using STL is easier to modify and read. Because the code is shorter, many basic work codes have been componentized.

STL Composition
STL has three core components: container, algorithm, iterator, container adapter, function object ), in addition, there are other standard STL components.

Container ):

Containers are the methods for organizing data in memory, such as arrays, stacks, queues, linked lists, or binary trees (but these are not STL standard containers ). Containers in STL are a data structure that stores a finite set of T (Template) values. The internal implementation of containers is generally a class. These values can be objects, if the data type T represents class.

Algorithm (algorithm ):

An algorithm is a behavior or function that is used to process its content in a container in various ways. For example, there are algorithms for sorting, copying, searching, and merging container content. In STL, algorithms are represented by template functions. These functions are not a member function of the container class. Instead, they are independent functions. One of the surprising features is that its algorithms are so common. It can be used not only for STL containers, but also for common C ++ arrays or containers specified by any other application.
Iterator ):

Once a container type and data behavior (algorithm) are selected, the only thing that you need to do is to use the iterator to interact with each other. You can regard the iterator as a normal pointer to elements in the container. You can increment the iterator like a pointer to point it to each subsequent element in the container in turn. An iterator is a key part of STL because it connects algorithms with containers.

Next I will introduce thisThree main components.

Container
Containers in STL include queue containers and associated containers, container adapters (congtainer adapters: Stack, queue, priority queue), bit_set, and string_package.
In this article, I will introduce the list, vector, deque and other queue containers, and association containers such as set, multisets, map, and multimaps. There are seven basic container classes.
Queue container (ordered container): the queue container stores the T-type value set in a linear arrangement. Each member of the queue has its own unique position. Ordered containers include vector type, double-end queue type, and list type.
Basic container-ordered container
Vector (vector container class ):# Include <vector>, vector isDynamic ArrayIs the class template of the basic array. Many basic operations are defined internally. Since this is a class, it will have its own constructor. Four constructor types are defined in the vector class:

The default constructor constructs an empty vector with an initial length of 0,
For example, vector <int> V1;
Constructor with a single integer parameter, which describes the initial size of a vector. This constructor also has an optional parameter, which is an instance of the T type and describes the initial values of each member of each vector;
For example: vector <int> V2 (init_size, 0); if it is pre-defined: int init_size; its member values are initialized to 0;
Copy the constructor to construct a new vector. As a complete copy of an existing vector,
For example, vector <int> V3 (V2 );
A constructor with two constant parameters generates a vector with an initial value as an interval. The interval is specified by a semi-open interval [first, last] (the display of MS word may be problematic, first is a left square bracket, last is a right circle bracket.
For example, vector <int> V4 (first, last)
The following example uses the fourth constructor. You can try other methods on your own.

// Stl_cpp_7.cpp
// Program: initialization demo
# Include <cstring>
# Include <vector>
# Include <iostream>
Using namespace STD;
Int ar [10] = {12, 45,234, 64, 12, 35, 63, 23, 12, 55 };
Char * STR = "Hello World ";
Int main (void)
{
Vector <int> vec1 (AR, Ar + 10); // first = AR, last = Ar + 10, excluding Ar + 10
Vector <char> vec2 (STR, STR + strlen (STR); // first = STR, last = STR + strlen (STR), excluding the last
Cout <"vec1:" <Endl;
// Print vec1 and vec2. const_iterator is an iterator.
// Of course, you can also use for (INT I = 0; I <vec1.size (); I ++) cout <VEC [I]; Output
// Size () is a member function of the vector.
For (vector <int >:: const_iterator P = vec1.begin (); P! = Vec1.end (); ++ P)
Cout <* P;
Cout <"\ n" <"vec2:" <Endl;
For (vector <char >:: const_iterator p1 = vec2.begin (); P1! = Vec2.end (); ++ P1)
Cout <* P1;
Getchar ();
Return 0;
}

To help understand the concept of vectors, we have written a small example, where the member functions of vector are used: Begin (), end (), push_back (), assign (), front (), back (), erase (), empty (), at (), size ().
// Stl_cpp_8.cpp
# Include <iostream>
# Include <vector>
Using namespace STD;
Typedef vector <int> intvector; // custom type intvector
// Test the function of the vector container.
Void main (void)
{
// The vec1 object is initially empty.
Intvector vec1;
// The vec2 object initially has 10 elements with a value of 6.
Intvector vec2 (10, 6 );
// The vec3 object initially has 3 elements with a value of 6, copying the structure
Intvector vec3 (vec2.begin (), vec2.begin () + 3 );
// Declare a bidirectional iterator named I
Intvector: iterator I;
// Display data in vec1 from front to back
Cout <"vec1.begin () -- vec1.end ():" <Endl;
For (I = vec1.begin (); I! = Vec1.end (); ++ I)
Cout <* I <"";
Cout <Endl;
// Display data in vec2 from the beginning to the back
Cout <"vec2.begin () -- vec2.end ():" <Endl;
For (I = vec2.begin (); I! = Vec2.end (); ++ I)
Cout <* I <"";
Cout <Endl;
// Display data in vec3 from front to back
Cout <"vec3.begin () -- vec3.end ():" <Endl;
For (I = vec3.begin (); I! = Vec3.end (); ++ I)
Cout <* I <"";
Cout <Endl;
// Test the function for adding and inserting members. The vector cannot be inserted before.
Vec1.push _ back (2); // Add a member from the end
Vec1.push _ back (4 );
Vec1.insert (vec1.begin () +); // insert member 5 at the first position of vec1
// Insert all members of vec3 from the first position of vec1
Vec1.insert (vec1.begin () + 1, vec3.begin (), vec3.end ());
Cout <"after push () and insert () now the vec1 is:" <Endl;
For (I = vec1.begin (); I! = Vec1.end (); ++ I)
Cout <* I <"";
Cout <Endl;
// Test the value assignment function
Vec2.assign (8, 1); // assign a value to vec2 again. The initial values of the eight members are 1.
Cout <"vec2.assign (8, 1):" <Endl;
For (I = vec2.begin (); I! = Vec2.end (); ++ I)
Cout <* I <"";
Cout <Endl;
// Test the reference class function
Cout <"vec1.front () =" <vec1.front () <Endl; // The 0th member of vec1
Cout <"vec1.back () =" <vec1.back () <Endl; // The last member of vec1
Cout <"vec1.at (4) =" <vec1.at (4) <Endl; // the fifth member of vec1
Cout <"vec1 [4] =" <vec1 [4] <Endl;
// Test removal and Deletion
Vec1.pop _ back (); // remove the last Member from vec1
Vec1.erase (vec1.begin () + 1, vec1.end ()-2); // delete a member
Cout <"vec1.pop _ back () and vec1.erase ():" <Endl;
For (I = vec1.begin (); I! = Vec1.end (); ++ I)
Cout <* I <"";
Cout <Endl;
// Display the sequence status information
Cout <"vec1.size ():" <vec1.size () <Endl; // print the number of Members
Cout <"vec1.empty ():" <vec1.empty () <Endl; // clear
}

 

Push_back () is a standard function that puts data into a 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 to let the loop run correctly -- the pointer it returns points to the data closest to the array boundary.

In Java, the concept of vectors also exists. A vector in Java is a collection of objects. Each element does not have to be of the same type. It can be added or deleted and cannot be directly added to the original data type.

Double-end Queue (qeque container class): # include <deque>
The deque container class is similar to the Vector class and supports random access and fast insertion and deletion, it takes linear time to operate at a certain position in the container. Unlike vector, deque also supports data insertion from the start end:
Push_front (). In addition, deque does not support operations similar to capacity () and reserve () of vector.

// Stl_cpp_9.cpp
# Include <iostream>
# Include <deque>
Using namespace STD;
Typedef deque <int> intdeque; // some people hate this definition.
// Display all the elements of the deque queue from the front to the back
Void put_deque (intdeque deque, char * name)
{
Intdeque: iterator pdeque; // still use iterator output
Cout <"the contents of" <name <":";
For (pdeque = deque. Begin (); pdeque! = Deque. End (); pdeque ++)
Cout <* pdeque <"; // note that there is a" * "number. If there is no" * "number, an error is returned.
Cout <Endl;
}
// Test the deqtor container Function
Void main (void)
{
// The deq1 object is initially empty.
Intdeque deq1;
// The deq2 object initially has 10 elements with a value of 6.
Intdeque deq2 (10, 6 );
// The deq3 object initially has three elements with a value of 6.
// Declare a bidirectional iterator variable named I
Intdeque: iterator I;
// Display data in deq1 from the beginning to the back
Put_deque (deq1, "deq1 ");
// Display data in deq2 from the beginning to the back
Put_deque (deq2, "deq2 ");
// Add two elements to the deq1 Sequence
Deq1.push _ back (2 );
Deq1.push _ back (4 );
Cout <"deq1.push _ back (2) and deq1.push _ back (4):" <Endl;
Put_deque (deq1, "deq1 ");
// Add two elements from the front of the deq1 Sequence
Deq1.push _ Front (5 );
Deq1.push _ Front (7 );
Cout <"deq1.push _ Front (5) and deq1.push _ Front (7):" <Endl;
Put_deque (deq1, "deq1 ");
// Insert data in the middle of the deq1 Sequence
Deq1.insert (deq1.begin () + 1, 3, 9 );
Cout <"deq1.insert (deq1.begin () + 1, 3, 9):" <Endl;
Put_deque (deq1, "deq1 ");
// Test the reference class function
Cout <"deq1.at (4) =" <deq1.at (4) <Endl;
Cout <"deq1 [4] =" <deq1 [4] <Endl;
Deq1.at (1) = 10;
Deq1 [2] = 12;
Cout <"deq1.at (1) = 10 and deq1 [2] = 12:" <Endl;
Put_deque (deq1, "deq1 ");
// Remove an element from the front and back of the deq1 Sequence
Deq1.pop _ Front ();
Deq1.pop _ back ();
Cout <"deq1.pop _ Front () and deq1.pop _ back ():" <Endl;
Put_deque (deq1, "deq1 ");
// Clear the 2nd elements in deq1
Deq1.erase (deq1.begin () + 1 );
Cout <"deq1.erase (deq1.begin () + 1):" <Endl;
Put_deque (deq1, "deq1 ");
// Assign values to deq2 and display them
Deq2.assign (8, 1 );
Cout <"deq2.assign (8, 1):" <Endl;
Put_deque (deq2, "deq2 ");
}

The above demonstrates how deque performs insert and delete operations, such as erase () and assign (), which are available in most containers. For more operations on deque, see the appendix.

Table (list container class): # include <list>
List is also called a linked list. It is a bilinear list. It can only be accessed in sequence (from Back to Back or from back to forward). Figure 2 is the data organization form of list. One obvious difference from the previous two container classes is that they do not support random access. To access the items at a subscript in a table, the cycle starts from the header or the end of the table (close to the end of the table. The subscript budget operator [] is missing.

At the same time, the list still contains basic functions such as erase (), begin (), end (), insert (), push_back (), and push_front, next we will demonstrate other functions of list.

Merge (): merges two sort lists;
Splice (): concatenates two lists;
Sort (): sort the list;

// Stl_cpp_10.cpp
# Include <iostream>
# Include <string>
# Include <list>
Using namespace STD;
Void printit (list <int> N)
{
For (list <int >:: iterator iter = n. Begin (); iter! = N. End (); ++ ITER)
Cout <* ITER <"; // use the iterator for output Loop
}
Void main (void)
{
List <int> listn1, listn2;
// Initialize listn1 and listn2
Listn1.push _ back (123 );
Listn1.push _ back (0 );
Listn1.push _ back (34 );
Listn1.push _ back (1123 );
// Now listn1: 123,0, 34,1123
Listn2.push _ back (100 );
Listn2.push _ back (12 );
// Now listn2: 12,100
Listn1.sort ();
Listn2.sort ();
// Sort listn1 and listn2
// Now listn1: 12,100, listn2:
Printit (listn1 );
Cout <Endl;
Printit (listn2 );
Listn1.merge (listn2 );
// After merging the two sorting lists, listn1: 34,100,123,112, 3
Cout <Endl;
Printit (listn1 );
Cin. Get ();
}

The above section does not demonstrate the usage of the splice () function. It is a little troublesome to use. Figure 3 shows the splice function. Insert a list to another list. The list container class defines three versions of the splice () function: splice (Position, list_value );
Splice (Position, list_value, PTR );
Splice (Position, list_value, first, last );

List_value is an existing list and will be inserted into the source list. position is an iteration parameter. It currently points to a specific position in the list to be spliced.

Listn1: 12,100, listn2:

Execute listn1.splice (find (listn1.begin (), listn1.end (), 0), listn2); then, listn1 will change to 1123. Insert listn2 to the element 0 of listn1. The find () function finds the position of the element 0 in listn1. It is worth noting that after the splice is executed, the list_value will no longer exist. In this example, listn2 will no longer exist.
In the second version, PTR is an iterator parameter. The execution result is to insert the value pointed to by PTR directly before the position currently pointed. this inserts only one element into the source list.
The first and last versions of the third version are also iterator parameters and are not equal to list_value.begin (), list_value.end (). First refers to the first element of the column to be inserted, and last refers to the last element of the column to be inserted.

If listn1: 123,0, 34,1123 listn2: 12,43, 87,100, after the following functions are executed, listn1.splice (find (listn1.begin (), listn1.end (), 0), ++ listn2.begin (), -- listn2.end ());
Listn1: 123,43, 87,0, 34,1123 listn2: 12,100

In addition to vector, deque, and list, other ordered containers include slist, bit_vector, and so on.

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.