当前位置:网站首页>Simulate and implement common interfaces of string class
Simulate and implement common interfaces of string class
2022-07-25 23:14:00 【some scenically beautiful place】
One : understand string Class private
private:
char* _str;
size_t _size;// The effective length of the string
size_t _capacity;// Space to store the maximum effective length of the string Two . Function realization
2.1 Constructors
// Full default constructor
string(const char* s = "")
:_size(strlen(s))
,_capacity(strlen(s))
{
_str = new char[strlen(s)+1];
strcpy(_str, s);
}2.2 Copy structure
// Implement deep copy problem
string(const string& s)
:_size(strlen(s._str))// Prevent space waste
, _capacity(_size)
{
_str = new char[_size + 1];
strcpy(_str, s._str);
}2.3 Destructor
~string()
{
if (_str)
{
delete[] _str;
_str = nullptr;
_size = _capacity = 0;
}
}2.4 Return string
The application is c Returns a string in the form of
// Return string
const char* c_str()const// This is not const and const Can call
{
return _str;
}2.5 Return string length
// Return string length
size_t size()const
{
return strlen(_str);
}2.6 heavy load =
// heavy load =
string& operator=(const string s)
{
if (this != &s)// Avoid wasting unnecessary time
{
char* tmp = new char[s._capacity + 1];
strcpy(tmp, s._str);
_str = tmp;
_size = s._size;
_capacity = s._capacity;
}
return *this;
}2.7 heavy load []
// heavy load []
char& operator[](size_t pos)
{
assert(pos < strlen(_str));
return _str[pos];
}2.8 Capacity expansion reserve and resize
// Realization reserve
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;// Release _str Otherwise, there will be a risk of memory leakage
_str = tmp;
_capacity = n;
}
}// Realization resize
void resize(size_t n, char ch = '\0')
{
if (n < _size)// Shrinkage capacity
{
_size = n;
_str[n] = '\0';
}
else
{
if (n > _capacity)
{
reserve(n);
}
strncpy(_str + _size, _str + n, ch);
_size = n;
_str[_size] = '\0';
}
}2.9 Realize the end insertion character (push_back) Or string (append)
// Realization push_back()
void push_back(char ch)
{
// Capacity expansion
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
_str[_size] = ch;
++_size;
_str[_size] = '\0';
}// Realization append
void append(const char* str)
{
size_t len = strlen(str);
// Judge whether to expand capacity
if (_size + len > _capacity)
{
reserve(_size + len);
}
strcpy(_str + _size, str);
_size += len;
}// Realization +=
string& operator+=(char ch)
{
// Reuse
push_back(ch);
return *this;
}
// Realization +=
string& operator+=(const char* str)
{
append(str);
return *this;
}2.10 Realize random insertion (insert) And random deletion (erase)
// Implement insert
string& insert(size_t pos, const char* str)
{
// Judge pos Is it legal
assert(pos <= _size);
// Judge whether to expand capacity
size_t len = _size + strlen(str);
if (len > _capacity)
{
reserve(len);
}
size_t end = _size + strlen(str);
while (end > pos + strlen(str)-1)
{
_str[end] = _str[end-strlen(str)];
end--;
}
strncpy(_str + pos, str, strlen(str));
_size = len;
return *this;
}Here it is private Define a npos
Initialize outside the class as -1;
const static size_t npos;string& earse(size_t pos, size_t len = npos)
{
assert(pos < _size);
if (len == npos || pos + len > _size)
{
_str[pos] = '\0';
_size = pos;
}
else
{
size_t begin = pos + len;
while (begin <= _size)
{
_str[begin - len] = _str[begin];
begin++;
}
_size -= len;
}
return *this;
}2.11 Realization find
//1. Find character
size_t find(const char ch, size_t pos = 0)
{
for (; pos < _size; pos++)
{
if (ch == _str[pos])
{
return pos;
}
}
return npos;
}
//2. Find string
size_t find(const char* s, size_t pos = 0)
{
char* p = strstr(_str + pos, s);
if (p != nullptr)
{
return p - _str;
}
else
return npos;
}2.12 Implement the forward iterator
ordinary string Use iterator,const The use of embellishments const_iterator
So we should realize overloading
typedef char* iterator;
typedef const char* const_iterator;
//begin
iterator begin()
{
return _str;
}
const_iterator begin()const
{
return _str;
}
//end
iterator end()
{
return _str+_size;
}
const_iterator end()const
{
return _str + _size;
}
// Heavy load front ++
iterator operator++()
{
return ++_str;
}2.13 heavy load << and >>
This can only be done outside the class , Ensure that the left operand is cout
Here, we need to use friend functions to avoid errors .
Friends use :friend+ Function declaration . Just add this code to the class field .
// heavy load <<
ostream& operator<<(ostream& out, const string& str)
{
for (auto ch : str)// Traverse
{
out << ch;
}
return out;
}
// heavy load >>
istream& operator>>(istream& in, string& str)
{
char ch;
ch = in.get();// Read characters in buffer
// Avoid multiple expansion
char buff[128] = { '\0' };
size_t i = 0;
while (ch != ' ' && ch != '\n')
{
buff[i++] = ch;
if (i == 127)
{
str += buff;
i = 0;
memset(buff, '\0', 128);
}
ch = in.get();
}
str += buff;
return in;
}2.14 Overload ratio size
It uses C In language strcmp function .
bool operator==(const string& s1, const string& s2)
{
return strcmp(s1.c_str(), s2.c_str()) == 0;
}
bool operator>(const string& s1, const string& s2)
{
return strcmp(s1.c_str(), s2.c_str()) > 0;
}
bool operator<(const string& s1, const string& s2)
{
return strcmp(s1.c_str(), s2.c_str()) < 0;
}
bool operator!=(const string& s1, const string& s2)
{
return !(s1 == s2);
}
bool operator>=(const string& s1, const string& s2)
{
return !(s1 < s2);
}
bool operator<=(const string& s1, const string& s2)
{
return !(s1 > s2);
}边栏推荐
- Enterprise level inventory management system of code audit
- 如何获取广告服务流量变现数据,助力广告效果分析?
- [PTA] 7-24 minimum fraction (15 points)
- Experience of machine learning with Google Lab
- Computed and watch listening properties
- anaconda安装教程环境变量(如何配置环境变量)
- r语言绘图参数(R语言plot画图)
- Solution of phpstudy service environment 80 port occupied by process system under Windows
- Custom MVC principle
- Deploy flash based websites using Google cloud
猜你喜欢

栈与Stack类

PHP JSON variable array problem

POI特效 市场调研

@Import

AI首席架构师12-AICA-工业生产过程优化场景下产业落地解析

Tips for using (1)
![Explain in detail the addition (+) operation in JS, basic data type addition, reference data type addition, and the underlying operation rules, [] + {}, {} + []](/img/06/85a6ba450fc2637a4ac1cf6a630912.png)
Explain in detail the addition (+) operation in JS, basic data type addition, reference data type addition, and the underlying operation rules, [] + {}, {} + []

Analysis of the influence of ESM direction finding error on positioning error

Network Security Learning (XIV) IP protocol

Secure code warrior learning record (IV)
随机推荐
anaconda安装教程环境变量(如何配置环境变量)
Experience of machine learning with Google Lab
Network Security Learning (11) scanning and blasting
IPFs of Internet Protocol
类和对象(2)(6个默认成员函数)
Data filtering of MATLAB
Discuz atmosphere game style template / imitation lol hero League game DZ game template GBK
About using NPM command under the terminal, the installation error problem is solved (my own experience)
Network Security Learning (XIV) IP protocol
Zcmu--5015: complete the task
Tencent map API request source is not authorized, this request source domain name
Enabling partners, how can Amazon cloud technology "get on the horse and get a ride"?
理解的英文(言语理解)
Secure code warrior learning record (II)
PHP JSON variable array problem
Computed and watch listening properties
The difference between abstract classes and interfaces
Network Security Learning (XV) ARP
WebMvcConfigurationSupport
Flight control implementation of four rotor aircraft "suggestions collection"