当前位置:网站首页>STL value string learning
STL value string learning
2022-07-27 15:32:00 【51CTO】
Write it at the front
We finally came into contact with C++ Of STL 了 , This is a C++ A very important part of the module , You can say that , If you learn C++ I haven't learned STL, So your C++ There is a high probability that it is incomplete , We learn STL There are two levels of learning , The first is that you can use , The second is to know their bottom , As for the higher level , Now I haven't reached , I won't share it with you . Let's have a brief understanding first STL, Have a general understanding , Today's main content is string.
What is? STL
STL(standard template libaray- Standard template library ): yes C++ An important part of the standard library , Not just a reusable component library , and It is a software framework including data structure and algorithm . I have shared the knowledge of data structure with you before , Also with big family C I have written in English , But their usability is a little low , You're writing OJ Question time , Use C Language , You will find that sometimes you have to implement the data structure yourself , Big guys also have such troubles , So appear STL, Generic programming is used , This is also the reason why we talked about templates earlier .
STL edition
We learn STL There are three versions , The functions inside are roughly the same .
- The original version Alexander Stepanov、Meng Lee The original version completed in HP Labs , This is the original STL
- P. J. edition Inherit HP edition , Slightly VS Series use , Code readability is low
- SGI edition Inherited from HP edition Ben . By GCC(Linux) use , Good portability , Reading is very high . We learn from the back STL To read part of the source code , The main reference is this version .
STL Components
STL Six components of , Let's look at the picture directly , The following content will involve , Here, let's first meet .

string
Let's get to know what is string, Simply speaking ,string stay C String we know in language , stay OJ in , Questions about strings are basically based on string Class , And in routine work , For simplicity 、 convenient 、 quick , Basically use string class , Few people use C String manipulation functions in the library . Because we often use , So the bosses turned this into a template class , In a sense ,string Do not belong to STL, It appeared much earlier .
know string
Have a look first STL On the inside string The classification of , We may wonder , How can there be four kinds here string, What kind of ,SLT Isn't it a template , Why here string It doesn't look like ... We solve these problems one by one .

Character encoding table
Talking about why there are four string Before ? We need to talk about what is a character encoding table . We all know that in the computer world , They only know 0 and 1, But in the real world , We have something similar to Chinese , English language , How can we connect the real world with the computer world ? This is the function of character coding table . The original character coding table was proposed by the United States , be called ASCII code , Chinese is not supported .

In order to encode the character table belonging to their respective countries , China has made up GBK, It uses 16 Binary of bit , But there is no unified standard in all countries , At this time, international organizations ISO Formulated the Unicode, It's also called the universal code .
We already know the history of the character table , The so-called four string It is to support characters with different bits , Yes , We're not the only ones char This is a character type , What we mainly learn seems string, Their four usages are roughly the same , Learned a , Just check the other documents .

string Is the template code
Yes , What we see string yes typedef Yes , That is, the parameter is char Template of type .

string The bottom of the
string The bottom layer of is a character array that can be dynamically developed , We must keep this in mind , Later, when we simulate the implementation, we follow this .

Use string
Now we can use string, We need the header file when using , But also need to release std Inside string, Say less and do more , Let's see .
Constructors
Now we can officially contact string What's in it , Be careful C98 in string There are seven constructors , But not all of us use it , Here I come to Jianshao with four .

Constructors | Function description |
string() | Construct an empty string |
string(const string& str) | Copy structure , Deep copy |
string(const char* s) | Construct by a string |
string(size_t n, char c) | Construct a structure that contains n individual c String of characters |
Now let's demonstrate .
string()

string(const char* s)

string(size_t n, char c)

string(const string& str)

length & Capacity
We know string The bottom layer is a dynamically opened array , that string Support the calculation we string Let's take a direct look at the functions of the effective length and capacity of objects .
size() & length()
Both of these are calculations string The effective length of the object , The only difference is the function name ,length() Is the initial method , The effective length of our string can be described as length, But the following hash table is a little unreasonable , So it adds size() This function , In order to keep the naming standard , That's it .


capacity()
Calculation is the capacity of the current object , That's the length of the array .

max_size()
This function is the maximum length of our string , Generally, it is not used by anyone , I'll just mention it here .

operator[] & at()
string Reload the [\] This operator , Can support subscript access , there at() Function and [\] It's the same thing , It's just an early version , There is no difference in function .

A cross-border visit
If we visit the next position of a valid character , Back to a \0, You don't know the bottom yet , But we know that the empty string contains a \0 Of , This is for compatibility C Language .

But if we cross the border ,VS The compiler will report an error .

Traverse string
Traverse string We have three ways , These three methods are also often used .
- Use Subscript
- Use iterator Let's focus on
- Use Range for
### The subscript access
string This class is overloaded [\] Of this operator , Plus string The bottom layer is an array , It supports random access ,


Iterators access
Maybe you're a little confused about iterators , I don't know what it is , Let's do that. , Let me just say that , The so-called iterator is that we traverse STL The most common method . Yes , You're not mistaken , Not all STL The bottom floor is a continuous space , In other words, subscript access is not universal .
string The iterator in is a native pointer , There are four kinds of iterators . Let's see .

Forward iterator
Here I directly use two ways to access , One is const Embellished , A modifiable .
The following is where the forward iterator points , Be careful end() The next position of the valid character pointed to .

You can modify what the iterator points to

If we want to modify what the iterator points to , Here you can see .

If we don't want to modify the data pointed to by the iterator , Can be called directly const Decorated iterators

The main application of this iterator is for those who don't want to modify string, Let's look at applications .

reverse iterator
Finished talking about positive iterators , Here we will talk about what is a reverse iterator , Its function is also traversal string, It's just anti ergodic .

This iterator is modifiable , There is no change here .

Now there are other things that can be reversed const Decorated iterators , We can use it , Don't talk about the specific .

Range for
Range for It's simpler , But there is one flaw , It must be traversed at one time

It looks tall , In fact, the bottom layer is also the reuse of iterators , The reusable iterator here can be modified


push_back()
string It supports inserting a character at the end , If the capacity is not enough , The compiler will automatically expand .

string Expansion mechanism
We know string The bottom layer of is a dynamic array , Now we want to see how it expands .
From here we can see that , The expansion rules of different compilers are different ,VS Next is 1.5 Double expansion ,g++ yes 2 Double expansion , And at first VS Opened up 15 Space ,g++ Didn't drive

reserve()
Everybody knows , Expansion comes at a price , Sometimes you need to open up space again and copy the array , If we know the total space opened , Wouldn't it be better to open up in advance , This is what this function does .
- Just change the capacity
- Don't change size, That is, you can understand that it is only capacity expansion .

Be careful ,reserve() The space opened up by function is not necessarily the same as what we want , Memory aligned , But it's not bad .

But here are two questions , If our N What will happen if it is larger than the existing capacity , What if it's smaller ? Here we discuss .
N > capacity
This is the same as the one above , It will automatically expand , Only change capacity, Don't change size.

N < capacity
If this happens , Nothing will change .

resize()
The function of this function can be seen from the name that it is reset size, in other words , Let's reassign the place of the trailing data , If there's not enough space , The compiler will automatically expand . But here are two functions , It is essentially a default function .


void resize (size_t n)
This is a reset N Space , Start counting from the beginning , Count to the subscript N The place of , This and all subsequent reset spaces become \0. There are three situations . Here we will discuss two common situations , The third is capacity expansion .

Situation 1

Situation two

Here I will give a summary , So-called resize Is to change the position after the last position of the effective element , Change the subscript to N, The distance from the original effective position , All become \0.
void resize (size_t n, char c)
This is even simpler , There is nothing to say , It also conforms to the above two rules , It also meets the insufficient expansion rules . Is to put the default \0 Change to the characters we want , There is no other explanation here .

clear()
Clean up valid characters ,VS There will be no volume reduction under , Look at the compiler's choice .

append()
We found that ,push_back Tail insertion is ok , But it supports inserting a character , We want to insert a string , Can you ,string This interface is also provided . Let's briefly introduce the longest used ones .

append() | Function description |
string& append (const string& str); | Tail insert one string object |
string& append (const char* s); | Insert a string at the end |
template string& append (InputIterator first, InputIterator last); | Use iterators to tail |
Let me demonstrate these functions directly , The usage is relatively simple , The new iterator tail insertion here is something we haven't seen before , Use it here alone .

string& append (InputIterator first, InputIterator last)
This is quite easy , It is a tail insert first To last The content of , There is nothing magical , To the next few blogs , We'll focus on iterators .

operator+=
Relative to the above append, This is what we often use , And easier to understand .

We will often use this .

insert()
In general , We don't use this function , Are the use of tail insertion , But in order to let you know , Take it out here for everyone , Give you a brief introduction of the commonly used .

insert() | Function description |
string& insert (size_t pos, const string& str); | stay pos Position insert a string |
string& insert (size_t pos, const char* s); | |
iterator insert (iterator p, char c); |
If you can use it .

erase()

This is to delete the subscript from pos Count back len Characters , If you don't pass characters, delete npos individual , there npos Is a static constant , The data is very big .


As for the iterator, I won't show you .
swap()
string There's something inside swap Functional , Of course, we std The one in can also be used , Just need to take place deep copy , It's a little inefficient .

c_str()
This function returns the pointer of this array , At work , Some do not accept string The pointer to , It's here string The pointer inside , It may not be of much use now .

find()
find() Is to find string Is there any character or string we want in it , The default is from subscript 0 At the beginning , What is returned is the subscript of the character or the head position of the string , If you can't find it, you'll return npos.



One more rfind() function , This is from string Object to find , I won't share it with you here .
substr()
This can be said to be a function of string truncation , from pos The position starts to cut ,len Characters , Here is also a default function .


getline()
We all know ,>> The operator ends when it encounters a space , Here for string It's the same .

This function is not string Peculiar , stay std Inner seal .

边栏推荐
- STM32 can communication filter setting problem
- TL431-2.5v基准电压芯片几种基本用法
- Cap theory and base theory
- Unity性能优化------渲染优化(GPU)之Occlusion culling(遮挡剔除)
- MySQL interview 40 consecutive questions, interviewer, if you continue to ask, I will turn my face
- EMC design scheme of USB2.0 Interface
- Sword finger offer merges two sorted linked lists
- npm install错误 unable to access
- Leetcode-1737-满足三条件之一需改变的最少字符数
- Do you really understand CMS garbage collector?
猜你喜欢

IJCAI 2022杰出论文公布,大陆作者中稿298篇拿下两项第一
MOS管防止电源反接的原理

EMC design scheme of CAN bus

华云数据打造完善的信创人才培养体系 助力信创产业高质量发展

Four kinds of relay schemes driven by single chip microcomputer

Unity mouse controls the first person camera perspective

Unity性能优化------渲染优化(GPU)之Occlusion culling(遮挡剔除)

How to edit a framework resource file separately

Leetcode-1737- minimum number of characters to change if one of the three conditions is met

The mobile terminal uses the list component of vantui. When multiple tab items are switched back and forth, the list is loaded many times, resulting in the failure of normal display of data
随机推荐
2022-07-27日报:IJCAI 2022杰出论文公布,大陆作者中稿298篇拿下两项第一
Zhou Hongyi: if the digital security ability is backward, it will also be beaten
Watermelon book machine learning reading notes Chapter 1 Introduction
仅做两项修改,苹果就让StyleGANv2获得了3D生成能力
《剑指Offer》两个链表的第一个公共结点
Leetcode 74. search two-dimensional matrix bisection /medium
Leetcode 341. flattened nested list iterator DFS, stack / medium
How to edit a framework resource file separately
Notice of Shenzhen Municipal Bureau of human resources and social security on the issuance of employment related subsidies for people out of poverty
LeetCode 783. 二叉搜索树节点最小距离 树/easy
Leetcode-1737-满足三条件之一需改变的最少字符数
多线程环境下CountDownLatch的用法
TL431-2.5v基准电压芯片几种基本用法
Lua study notes
STM32之CAN ---CAN ID过滤器分析
"Sword finger offer" linked list inversion
网络设备硬核技术内幕 路由器篇 (10) CISCO ASR9900拆解 (四)
Leetcode 190. reverse binary bit operation /easy
光电隔离电路设计方案(六款基于光耦、AD210AN的光电隔离电路图)
Distributed lock