Technology Sharing

STL Review - Sequence Containers and Container Adapters

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

STL Review

1. Common containers

How to introduce these containers, from the common interfaces, iterator types, and underlying implementations

insert image description here


Sequence Container

string

Strictly speaking, string does not belong to stl, it belongs to the C standard library

**Underlying implementation: **String is essentially a sequence table of char type. Because the specific implementation under different compilers is different, here is only a simple framework of my answer

class string
{
public:
    typedef char* iterator;
    typedef const char* const_iterator; 
private:
    char* _str; 		// 堆上开辟的顺序表空间
    size_t _size; 		// 有效字符个数
    size_t _capacity; 	// _str的空间大小

    static const size_t npos; // 最大字符串大小
};

const size_t string::npos = -1;

In the VS series, a string actually consists of a pointer, a union (an array and a pointer. If the string length is less than 16 bytes, the array allocated in advance will be used. If it is greater than 16 bytes, space will be allocated on the heap and the pointer will be used to point to it), size and capacity.

In g, string contains only a pointer to a space on the heap, a pointer to the space allocated for the string, a reference count, size and capacity. This reference count allows assignment and copying of these objects by shallow copying and increasing the reference count.

Iterator Types: Random Access Iterators

Commonly used interfaces:

Function nameFunction
size / lengthReturns the number of valid characters in a string
clear / reserver / resizeClear valid characters/reserve space/replace the number of valid characters to n, and fill the extra space with character c
operator[]Returns the character at position pos
push_back / append / operator =Insert the character c after the string / string / string
c_strReturns a C format string
find / rfind nposSearch for character c from position pos in the string (backward/forward) and return the position of the character in the string. If npos is not returned,
substrExtract n characters starting at position pos in str and return them.
operator