当前位置:网站首页>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 .
边栏推荐
猜你喜欢

Zhongang Mining: fluorite is rich in color and has great aesthetic value

I used fluent deskstop to build a Mars xlog log parsing tool

Li Kou daily question - day 42 -171. Excel table column serial number

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

Apifox学习记录

At the forefront of the times, Huawei aims at the wind and sea of digital finance

YOLOv7——论文简述

二级倒立摆系统的稳定控制与仿真(Matlab/Simulink)

《STL仿函数》priority_queue模拟实现

Data warehouse: Exploration and practice of integrating flow and batch
随机推荐
PHP 防止或检测页面被刷新 post重复提交问题
引擎提示Alias HeroDB跟游戏引擎启动异常怎么解决?
传奇私服GOM引擎启动M2提示:[X-FKGOM] 已经加载成功卡住的怎么处理?
mysql之外键操作_级联操作
Installation and login installation
安防摄像头互联网直播方案LiveGBS设计文档
How about opening an account for Huatai Securities? Is it safe
100 lines of code thoroughly analyze RPC principle
《STL容器篇》-List模拟实现(三种反向迭代器)
Jupyternotebook运行到指定行
YOLOv7——论文简述
swing-[MyNote]-实现像IDEA一样的定位scroll from souce功能
Alibaba cloud cloud box and exclusive region passed the comprehensive capability assessment of trusted cloud and proprietary cloud for the first batch of full marks
Mycms we media mall v3.5 release, new free plug-ins
abap ALV总结整理
LiveGBS-摄像机网页低延时无插件直播实现
事件抽取文献整理(2020-2021)
实现OPC UA publish/subscribe单次发送
BGP routing principles
7.20 codeforces round 763 (Div. 2) C (two points) d (mathematical expectation) Backpack + tree DP review