A Brief Introduction to STL class in Mark C ++

Source: Internet
Author: User

SGI-- Silicon Graphics [Computer System] Inc. Silicon graph [Computer System] Company.

STL-- Standard Template Library: Standard Template Library.

Container Concept

The STL container is to implement the most commonly used data structures.

A container is a collection of specific types of objects. According to the characteristics of data arrangement in containers, containers can be divided into two types: sequence and associative.

IteratorIs a data type that checks elements in a container and traverses elements. It provides pointer-like functions to visit the container content.

# Include

For example:

Std: vector IntVector;

Std: vector : Iterator first = IntVector. begin ();

// Begin () gets the Iterator pointing to the beginning of the vector. * first gets the value of the first element.

Std: vector : Iterator last = IntVector. end ();

// End () gets the Iterator pointing to the end of the vector. * The last element is obtained.

Sequential container

The so-calledSequential container, Where the elements can be ordered, but not necessarily sorted ). The array is a sequence Container built into the C ++ language. STL also provides vector, list, And deque (double-ended queue ). The difference lies in the method of accessing elements and the running cost of adding or deleting element-related operations.

The standard library also provides three container adapters. The so-called adapters adapt to the basic container types by defining new operation Interfaces Based on the operations provided by the original container types. Sequence container adapters include stack, queue, priority_queue, and other sequence containers. The stack and queue are technically classified as a adapter because they only change the deque into a new one. priority_queue is a queue with priority management.

1. Vector

1. Basic concepts of vector

Vector is a dynamic array model that replaces the C array with the standard C ++. It maintains a continuous linear space.

The data structure adopted by vector is very simple: linear continuous space. It points the start and finish of two iterators to the currently used range in the configured continuous space, and points the end_of_storage of the iterator to the end of the whole continuous space (including the standby space.

The key to the implementation of vector is its control of the size and the efficiency of data movement during redistribution. Once the original space of the vector is used up, it is unwise to expand the space of only one element for each new element added to the client. Because the so-called extended control (no matter how big) is a big project of "Configuring new space (malloc), copying mobile data (memcpy), and releasing old space (free)", the time cost is very high, some preplanned Space Configuration policy should be adopted.

Note: the so-called dynamic increase is not to continue with the new space after the original space (because there is still space available for configuration after cannot be guaranteed), but to allocate the original size twice each time. Therefore, any operations on the vector, once the control is reconfigured, all iterators pointing to the original vector will become invalid.

Vector maintains a continuous linear space. Therefore, the vector iterator provides the common pointer function and supports Random Access. That is, the vector provides the Random Access Iterators.

2. vector class template std: member function of vector

# Include

Std: vector Vec;

Std: vector Vec (size );

Std: vector Vec (size, value );

Std: vector Vec (myvector );

Std: vector Vec (first, last );

Operators: = ,! =, <=, >=, <,>, []

Assign (first, last): replaces the vector element with the element specified by iterator first and last.

Assign (num, val): replace the vector element with the num copy of val

At (n): equivalent to the [] Operator. It returns the element of position n in the vector. Because it has an out-of-bounds check, it is safer than [] index access.

Front (): returns the reference of the first element in the vector.

Back (): returns the reference of the last element in the vector.

Begin (): returns the iterator of the first element in the vector.

End (): returns the next iterator of the last element in the vector (end cursor only and cannot be referenced)

Max_size (): Maximum capacity of the returned vector type (2 ^ 30-1 = 0x3FFFFFFF)

Capacity (): the size of the space currently opened by the return vector (<= max_size, related to the dynamic memory allocation policy of the vector)

Size (): number of existing elements in the returned vector (<= capacity)

Clear (): deletes all elements in a vector.

Empty (): returns true if the vector is null.

Erase (start, end): deletes elements within the specified range of the iterator start end.

Erase (I): Delete the elements pointed to by iterator I

Erase () returns the iterator pointing to the next position of the last deleted element.

Insert (I, x); insert x before the position specified by iterator I

Insert (I, n, x): insert n copies of x to the position specified by iterator I.

Insert (I, start, end): inserts the values in the range specified by the iterator start and end before the position specified by the iterator I.

Push_back (x): Push (insert) x to the end of the vector.

Pop_back (): the last element of the pop-up (delete) vector

Rbegin (): returns a reverse iterator that points to an element that crosses the last element in the vector.

Rend (): returns a reverse iterator pointing to the first element in the vector.

Reverse (): reverse element order

Resize (n, x): Change the vector size to n, and assign the initial value of the new element to x.

Swap (vectorref): swap the content of two vectors

3. Dynamic string type std: string

String is a dynamic string model of a standard C ++ string that is recommended to replace a C string (an array of zero-ending characters ). .

# Include

Std: string str1;

Std: string str3 (str2 );

Std: string str2 ("this is a string ");

The following general operations are not listed for the same vector.

Operators: +, + =

Length (): Same as the size () function

Data (): returns a string pointer.

C_str (): returns a C-style string pointer.

The process of c_str () is to call terminate () first, and then return data (). Therefore, if you have high requirements on efficiency and your processing does not need to end in/0, you 'd better choose data (). However, for General C functions, you must use const char * as the input parameter and use the c_str () function.

Operator =: Value assignment operator

Append (): append string

Replace (): replace character

Copy (): copy your num characters to str (starting from index ).

Find (): searches for a specified character in the string, and returns an index number based on 0.

Rfind (): Reverse Lookup

Find_first_of (): searches for any character in the substring and returns the first position.

Find_first_not_of (): searches for any character that does not contain the substring and returns the first position.

Find_last_of (): searches for any character in the substring and returns the last position.

Find_last_not_of (): searches for any character that does not contain the substring and returns the last position.

Substr (n1, len): obtain a substring whose length starts from n1 and is len.

Comparison string (all Relational operators supported)

Compare comparison string

Operator + String concatenation

Operator + = add Operators

Operator = judge whether it is equal

Operator! = Judge whether it is not equal

Operator <判断是否小于< p>

Operator> Read strings from the input stream

Operator < <字符串写入输出流< p>

Getline reads a row from the input stream

Ii. list

1. Basic concepts of list

Compared with the continuous linear space of vector, list is much more complex. Compared with vector, list allows fast insertion and deletion, and one element is inserted or deleted each time, configure or release an element space. Therefore, the use of list for space is absolutely accurate and will not be wasted at all. In addition, for element insertion or removal at any position, list is always a constant time.

A list can no longer use a normal pointer as a vector as an iterator, because its nodes do not guarantee continuous existence in the storage space. The list iterator must be able to point to the list node and perform operations such as increment, decrease, value, and member access correctly. The "list iterator correctly increments, increments, values, and Members" operation means that the list iterator points to the next node and the list iterator points to the previous node, the value is the data value of the node, and the member is the member of the node.

List is not onlyBidirectionalLinked list, but it is stillRingTwo-way linked list. Therefore, it only needs a pointer to implement the entire linked list. Because list is a double linked-list, the iterator must be able to move forward and backward. Therefore, list provides Bidirectional Iterators.

List has an important property: insert and splice operations do not invalidate the original list iterator. This is not true in the vector, because the insert operation of the vector may cause memory reconfiguration, resulting in all the original iterators being invalid. Even the list element deletion operation (erase) fails only the iterator that points to the deleted element. Other iterators are not affected.

2. linked list template std: list member function

# Include

Std: list Lst;

Std: list Lst (size );

Std: list Lst (size, value );

Std: list Lst (mylist );

Std: list Lst (first, last );

The following general operations are not listed for the same vector.

Push_front (x): Push (insert) element x to the head of the linked list.

Pop_front (): the first element of the pop-up (delete) linked list

Merge (listref): inserts all elements in the linked list referenced by listref into the linked list. You can specify the merging rules.

Splice (): connects the lst to the position of the pos

Remove (val): delete all elements with val values in the linked list.

Remove_if (pred): Delete the pred in the linked list as the true element.

(Predicates are the descriptions of element storage and retrieval, such as std: less <>, std: greater <>, which are arranged in descending/ascending order, you can also define your own predicates)

Sort (): sorts linked lists based on default predicates.

Sort (pred): sorts linked lists based on given predicates.

Unique (): deletes all duplicate elements in the linked list.

Unique (pred): deletes all repeated elements based on the pred, so that there are no repeated elements in the linked list.

Note: vector and deque support random access, while list does not support random access, so [] access is not supported!

Iii. deque

1. Basic concepts of deque

Vector is the continuous linear space of one-way open, and deque is the continuous linear space of the middle bidirectional open. The so-called bidirectional opening means that you can insert and delete elements at the beginning and end. From a technical point of view, vector can also be operated on both ends of the head and tail, but its header operation efficiency is odd and unacceptable.

The biggest difference between deque and vector is that deque allows the opposite end to insert or remove elements within the constant time, And deque does not have the so-called capacity concept, because it is dynamically combined with consecutive segments, a new space can be added and linked at any time. In other words, things like "reconfigure a larger space due to insufficient old space, copy elements, and release the old space" won't happen in deque. Therefore, deque does not need to provide the so-called space reservation (reserved) function.

Although deque also provides Random Access Iterator, its Iterator is not a common pointer, and its complexity is different from that of vector. Of course, this involves various operational aspects. Therefore, unless necessary, we should try to use vector instead of deque. For the highest efficiency, deque can be completely copied to a vector first, sorted by vector (using the STL sort algorithm), and then copied back to deque.

Deque is composed of quantitative continuous spaces of a segment. Once it is necessary to add new space at the front or end of deque, a quantitative continuous space is configured, and the string is connected to the entire deque header or tail end. The biggest task of deque is to maintain the overall continuity in the quantitative continuous space of these segments and provide random access interfaces. Avoiding the "reconfiguration, replication, and release" cycle, the cost is a complex iterator architecture.

2. Double-end queue template std: deque member function

# Include

Std: deque Deq;

Std: deque Deq (size );

Std: deque Deq (size, value );

Std: deque Deq (mydeque );

Std: deque Deq (first, last );

The member functions are as follows:

Operators: [] used to access a single element in a two-way queue

Front (): returns the reference of the first element.

Push_front (x): Push (insert) element x to the header of the bidirectional queue

Pop_front (): the first element of the two-way queue is displayed (Deleted ).

Back (): returns the reference of the last element.

Push_back (x): Push (insert) element x to the end of the bidirectional queue.

Pop_back (): the last element of the two-way queue is displayed (Deleted ).

4. deque-based sequential container adapter stack and queue (priority_queue)

Stack

1. Basic concepts of stack

Stack is a data structure of First In Last Out (FILO). It has only one exit. Stack allows you to add, remove, and obtain the top element. However, there is no way to access other elements of the stack except the top. In other words, the stack does not allow random access.

STL uses deque as the underlying structure of the stack. the stack is formed by slight modifications to the opening of the head end during the deque sealing period.

The operation of inserting an element into a stack is called push, and the operation of element pop-up stack is called pop. All elements in and out of a stack must comply with the "first-in-first-out" condition. Only elements at the top of the stack can be used by the outside world. Stack does not provide the access function or the iterator.

2. Container adapter stack class std: stack member function

# Include

Stack to implement the following operations:

Std: stack Stk;

Type is the data type of the stack operation.

The container type used to implement the stack. The default value is deque. It can also be std: vector and std: list.

For example, std: stack > IntStack;

The member functions are as follows:

Top (): returns the reference of the top element.

Push (x): pushes elements to the stack (top)

Pop (): The top element of pop (delete)

Queue

1. Basic concepts of queue

Queue is a data structure of First In First Out (FIFO). It has two egress ports. Queue allows you to add, remove, and add elements from the bottom to obtain the top element. However, apart from adding at the bottom and extracting at the top, there is no other way to access other elements of queue. In other words, queue does not support random access.

STL uses deque as the underlying structure of the queue, and closes the exit at the bottom of deque and the entrance at the front end. A queue is formed after slight modification.

2. Container adapter queue class std: queue member function

# Include

Queue for first-in-first-out operations

Std: queue Que;

Type is the data type of queue operations.

For the container type used to implement the queue, the container can only be std: deque or std: list that provides the push_front operation. The default container type is std: deque.

The member functions are as follows:

Front (): returns the reference of the first element of the team.

Back (): returns the reference of the team end element.

Push (x): push (insert) element x to the end of the team

Pop (): the first element of the team is displayed (pop-up (delete) the first element of the Team)

Priority_queue

1. Basic concepts of priority_queue

Priority_queue is a priority queue, which allows you to set a priority for the elements stored in the queue. This queue does not directly place new elements at the end of the queue, but is placed before elements with lower priority. This provides a queuing policy. Standard library is used by default <操作符来确定他们之间的优先级关系。即权重大的排在队首。< p>

When priority_queue is used File.

2. Container adapter queue class std: priority_queue member function

# Include

Priority_queue for first-in-first-out operations

Std: priority_queue Pri_que;

Type is the data type of queue operations.

Container is the container type used to implement the queue. It can be std: vector, std: deque, which is based on deque by default.

Comp is a queuing policy. The default value is std: less <>, that is, before the element smaller than it is inserted.

For example, std: priority_queue , Std: greater > IntPriQue;

The member functions are as follows:

Top (): return the reference of the first (highest priority) element of the team.

Push (x): pushes elements to the queue (in line with the insert queue policy) (tail)

Pop (): the first (highest priority) element of the pop (delete) Team

Associated container

The so-called relational container is similar in concept to the relational database (which is actually much simpler): Each data (element) contains a key and a real value ). When an element is inserted into an associated container, the internal data structure of the container (which may be RB-tree or hash-table) is determined by its key value, place this element in the appropriate position using a specific rule. Associated containers do not have the so-called header and tail (only the maximum and minimum elements), so no push_back (), push_front (), pop_back (), pop_front (), begin (), end.

Generally, the internal structure of the correlated container is a balanced binary tree (balanced binary tree) to achieve good search efficiency. Balanced binary tree has many types, including AVL-tree, RB-tree, and AA-tree. Among them, RB-tree (red-black tree) is widely used in STL ).

The standard STL associated containers are divided into two categories: set and map, and the derivative multiset (Multi-key set) and multimap (Multi-key ing table ). The underlying mechanism of these containers is implemented using RB-tree (Red/black tree ). RB-tree is also an independent container, but it is not open for external use.

In addition, sgi stl provides an associated container that is not in the Standard Specification column: hash table (hash table, hash table ), as well as hash_set (hash set), hash_map (hash ing table), and hash_multiset (hash multi-key set) completed using this hash table as the underlying mechanism), hash_multimap (hash multi-key ing table ).

Map

Associated container std: map member function

# Include

Map creates a key-value ing

Std: map Mp;

Std: map Mp;

Key is the key value

Value is the ing value.

Optional. It is a key-Value Pair storage policy. For example, it can be std: less <>. Key-value ing pairs store key values from small to large.

The member functions are as follows:

Count (): returns the number of elements whose key value is the same as the key in the map.

Performance_range (): The function returns two iterators-one pointing to the first key-value key element and the other pointing to the last key-value key element.

Erase (I): deletes the elements (key-value pairs) at the position indicated by the iterator)

Lower_bound (): returns an iterator pointing to the first element of the key> = key in the map.

Upper_bound (): The function returns an iterator pointing to the first element of the key> key in the map.

Find (key): return the key-Value Pair iterator whose key value is key. If this ing is not available, the end cursor end () is returned ()

Note the [] Operator of map. When you try to reference a key that does not exist, a new key-value pair is created and the value is null.

General Algorithm (applicable to the above STL)

# Include

1. Non-correction Sequence Algorithm:

2. Sequence Correction Algorithm:

3. Sorting Algorithm:

4. Numerical Algorithm:


Related Article

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.