当前位置:网站首页>STL container -string Simulation Implementation
STL container -string Simulation Implementation
2022-07-23 07:03:00 【Li Fengxi】
One 、 This interface implementation includes
Member functions include :
string(const char* str = "")
~string()
void swap(string& s)
string(const string& s)// The traditional way of writing
string(const string& s)// Modern writing
string& operator=(const string& s)// The traditional way of writing
string& operator=(string s)// Modern writing
void reserve(size_t n)
void resize(size_t n, char ch = '\0')
void push_back(char ch)
void pop_back()
void append(const char* str)
const char* c_str()const
size_t size()const
size_t capacity()const
iterator begin()
iterator end()
const_iterator begin()const
const_iterator end()const
bool empty()const
void clear()
char& operator[](size_t pos)
const char& operator[](size_t pos)const
string& operator+=(char ch)
string& operator+=(const char* str)
string& insert(size_t pos, char ch)
string& insert(size_t pos, const char* str)
string& erase(size_t pos, int n = npos)
size_t find(char ch, size_t pos = 0)
size_t find(const char* str, size_t pos = 0)
Global functions include :
std::ostream& operator<<(std::ostream& out, const string& s)
std::istream& operator>>(std::istream& in, string& s)
bool operator>(const string& s1, const string& s2)
bool operator==(const string& s1, const string& s2)
bool operator>=(const string& s1, const string& s2)
bool operator<(const string& s1, const string& s2)
bool operator<=(const string& s1, const string& s2)
bool operator!=(const string& s1, const string& s2)Here I only select some interfaces for detailed analysis , Because other interfaces are really easy to implement . Because the mobile construction and mobile assignment belong to c++11 New scope of , This is not about , The author will c++11 The chapter supplements this part .
Two 、 The interface is fully implemented
https://gitee.com/zxlfx/c-code-warehouse/tree/master/2022_7_19
3、 ... and 、 Some interfaces are explained in detail
3.1 Traditional and modern writing methods of copy construction
string(const string& s)// The traditional way of writing { _str = new char[s._capacity + 1]; _capacity = s._capacity; _size = s._size; strcpy(_str, s._str); } void swap(string& s) { std::swap(_str, s._str); std::swap(_size, s._size); std::swap(_capacity, s._capacity); } string(const string& s)// Modern writing :_str(nullptr), _size(0), _capacity(0) { string temp(s._str); swap(temp); }The traditional way of writing is to open up space honestly , Then copy the data to the new space , The modern way of writing is to take out s Of _str, Call again string(const char* str = "") Generate temporary objects temp, Then exchange *this And temp Of _str,_size,_capacity. This is equivalent to making temp To help you create a copy object , Then take temp Resources for , but temp Destructors will be called when destroying , At this point it's _str It's the original this Of _str, So in exchange _str Before , Need to put this Of _str Set to empty , otherwise temp Crash when calling destructor .
3.2 Modern and traditional ways of assignment overloading
string& operator=(const string& s)// The traditional way of writing { if (this != &s) { char* temp = new char[s._capacity + 1]; strcpy(temp, s._str); delete[] _str; _str = temp; _size = s._size; _capacity = s._capacity; } return *this; } string& operator=(string s)// Modern writing { swap(s); return *this; }Compared with traditional writing , Modern writing is more concise , However, the following modern writing method will call copy construction in the scenario of assigning values to itself , The efficiency is not high , The traditional writing method adds the judgment of not assigning a value to yourself , Go straight back to *this.
3.3reserve and resize
void reserve(size_t n) { if (n > _capacity) { char* temp = new char[n + 1]; strcpy(temp, _str); delete[] _str; _str = temp; _capacity = n; } } void resize(size_t n, char ch = '\0') { if (n < _size) { _str[n] = '\0'; _size = n; } else { if (n > _capacity) { reserve(n); } else { for (size_t i = _size; i < n; i++) { _str[i] = ch; } _str[n] = '\0'; _size = n; } } }The functions of these two functions mainly refer to vs2019, about reserve, If n>capacity Increase capacity when ,n<capacity No shrinkage . about resize, If n<size, Just put size To adjust to n,n Greater than size, Explain to add data , test n>capacity Just expand to n, Then keep inserting ch to size==n.
3.4insert and erase
string& insert(size_t pos, char ch) { assert(pos <= _size); if (_size == _capacity) { reserve(_capacity == 0 ? 4 : _capacity * 2); } char* start = _str + pos; char* end = _str + _size; while (end >= start) { *(end + 1) = *end; end--; } _str[pos] = ch; _size++; return *this; } string& insert(size_t pos, const char* str) { assert(pos <= _size); size_t size = strlen(str); if (_size + size > _capacity) { reserve(_size + size); } char* start = _str + pos; char* end = _str + _size; while (end >= start) { *(end + size) = *end; end--; } strncpy(_str + pos, str, size); _size += size; return *this; } string& erase(size_t pos, int n = npos) { assert(pos < _size); if (pos + n >= _size) { _str[pos] = '\0'; _size = pos; } else { char* start = _str + pos; char* end = _str + _size; while (start < end) { *start = *(start + n); start++; } _size -= n; } return *this; }Here's the advice while Judging conditions use address comparison , If subscript comparison is used , Such as while(num>=pos) When pos by 0 when ,num by 0 when ,num Get into while, then --, here num Become the maximum value of the shaping , because num yes size_t Type of , Then it will still enter while, Cause the cycle to continue . And use the address to do while Judgment can well avoid such problems .
3.5<< and >> heavy load
std::ostream& operator<<(std::ostream& out, const string& s) { for (auto& a : s) { out << a; } return out; } std::istream& operator>>(std::istream& in, string& s) { s.clear(); int ch = 0; char buf[128] = { 0 }; int i = 0; while ((ch = in.get()) != ' ' && ch != '\n') { buf[i++] = ch; if (i == 127) { s += buf; memset(buf, '\0', sizeof(char) * 128); i = 0; } } s += buf; return in; }Overload here << when , Why not directly cout<<s.c_str() Well ? Instead, traverse s Well ? Mainly because of the following situations
When s by "1 4 6 a b \0 2 3 4", When printing, the following elements cannot be printed , You can only print 1 4 6 a b.
About >> Overloaded buf,buf Buffer here , If s constantly +=ch, Then it may be frequently expanded , Affect efficiency , And if ch In the buf in , If buf Full of , Just put buf Data into s in , At the same time to empty buf The data of , And will i Set as 0, Finally, don't forget to put the not full buf Data into s in .
3.6find( Find a character , And find substrings )
size_t find(char ch, size_t pos = 0) { for (size_t i = pos; i < size(); i++) { if (_str[i] == ch) { return i; } } return npos; } size_t find(const char* str, size_t pos = 0) { char* ret = strstr(_str + pos, str); if (ret != nullptr) { return ret - _str; } return npos; }Find a character , Traverse s that will do . Find substrings using c Library functions of a language strstr, because find Is the return subscript , and strstr Is the address that returns the substring , that pos be equal to ret-_str.
Four 、 Last
The above implementation is only for reference , If there are mistakes or doubts , Please also comment or chat with me in the comment area , thank !
About implementation details , Code in many places is easy to read , Here, only some points needing attention are selected for analysis , Follow up stl Containers will be introduced in turn vector、list、deque、map、set、unorderedmap、unorderedset Do please look forward to .
边栏推荐
- 1. Summary of strengthening learning foundation
- let和const解决了什么问题,两者的区别
- 472-82(22、165、39、剑指 Offer II 078、48. 旋转图像)
- One type and six methods of urllib
- 安装和登录安装
- STL adapter stack and queue
- How about opening an account for Huatai Securities? Is it safe
- thinkphp URL_MODE =0 普通模式 的具体用法
- Combing the docking process between the integration base and the business system
- MySQL --- 子查询 - 子查询概念、规范、分类
猜你喜欢

(ros_melody) using rviz for boundingbox visualization

Redis增强

TCP waves four times

第九章 使用图像数据

HMS Core Discovery第16期直播预告|与虎墩一起,玩转AI新“声”态

Apifox学习记录

事件抽取文献整理(2020-2021)

In the name of "upgrade", talk about the core technology of cloud native data warehouse analyticdb

第一章 回归,分类 & 聚类

Simple face detection using mediapipe and opencv
随机推荐
7.20 Codeforces Round #763 (Div. 2) C(二分) D(数学期望)背包+树形dp复习
HCDE城市闭门会南京站成功举办
Apifox learning record
Zlmediakit tries to solve the video splash screen problem of gb28181 (UDP mode)
第五章 传播训练
Zhongang Mining: fluorite is rich in color and has great aesthetic value
锅炉汽包温度控制系统设计(过程控制课程设计matlab/simulink)
电商项目如何解决线上优惠券超发(排错+解决方案)(荣耀典藏)
ABAP ALV steps
如何将监控画面嵌入微信公众号进行直播
XSS必备知识
BGP邦联实验
事件抽取文献整理(2020-2021)
电磁场与电磁波实验四 熟悉CST Studio软件在电磁领域的应用
TCP waves four times
Combing the docking process between the integration base and the business system
中年危机,不敢离职的职场爸爸,该如何面对生活的苟且
MySQL --- 子查询 - 子查询概念、规范、分类
100 lines of code thoroughly analyze RPC principle
ZLMediaKit尝试解决GB28181(UDP方式)的视频花屏问题