当前位置:网站首页>Introduction and Simulation Implementation of string class
Introduction and Simulation Implementation of string class
2022-07-19 11:39:00 【'pie pie'】
Catalog
2.string Class common interface
2.1. string Common constructions of class objects
2. 1string Class object capacity operation
2.3. string Class object modification operation
4.string The realization of the class
4.1 Deep and shallow copy problem
4.2.string Class common function implementation
1. Introduce
2.string Class common interface
2.1. string Common constructions of class objects

give an example :
vvoid test_string1()
{
string s1(10,'x');
string s2("hello world");
string s3(s2, 6, 3);// from s2 pass the civil examinations 6 Copy data from locations , If no length is specified , Then copy all the following data
string s4(s2.begin() + 1, s2.end());
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
}
int main()
{
test_string1();
return 0;
}
result :
xxxxxxxxxx
hello world
wor
ello world2. 1string Class object capacity operation



Add :resize,reserve Will not shrink , but resize Can reduce data , change size
2.3. string Class object modification operation

void test_string3()
{
string s1("http://www.com.cplusplus.com/reference/string/string/find/");
cout << s1.c_str() << endl;// obtain s1 String in
string s2 = s1.substr(5,5);// from s1 in pos Position copy Character , If no length is specified , Copy everything behind ;
cout << s2 << endl;
size_t pos1 = s1.rfind('f');// Find characters from back to front , Returns the subscript ,
size_t pos2 = s1.find("com", 12);// Subscript from front 12 Find string , Returns the subscript
cout << pos1 << " " << pos2 << endl;
}
result :
http://www.com.cplusplus.com/reference/string/string/find/
//www
53 25
string s;
getline(cin, s);// You can enter a string of characters , With spaces
cout << s << endl;3. summary :
string There are many functions in the class , And there are overloads , You can view the document :string - C++ Reference To learn
4.string The realization of the class
namespace LF
{
class string
{
public:
private:
char* _str;// Store string
size_t _size; // Number of valid characters
size_t _capacity; // The actual space to store valid characters
};
}4.1 Deep and shallow copy problem
First mask the copy constructor
namespace LF
{
class string
{
public:
typedef char* iterator;
typedef const char* const_iterator;
const_iterator begin() const
{
return _str;
}
const_iterator end() const
{
return _str + _size;
}
iterator begin()
{
return _str;
}
iterator end()
{
return _str + _size;
}
string(const char* str = "")// All default
: _size(strlen(str))
, _capacity(_size)
{
_str = new char[_capacity + 1];// to \0 Reserve space
strcpy(_str, str);
}
/*string(const string& s)// Mask this constructor
:_str(new char[strlen(s._str)+1])
{
strcpy(_str, s._str);
}*/
~string()// Destructor
{
if (_str)
{
delete[] _str;
}
}
const char* c_str() const// Returns the string ,const, Do not modify
{
return _str;
}
char& operator[](size_t pos)// Return value with &, The original data can be modified
{
assert(pos < strlen(_str));
return _str[pos];
}
const char& operator[](size_t pos) const// Do not modify the
{
assert(pos < _size);
return _str[pos];
}
size_t size() const
{
return _size;
}
size_t capacity() const
{
return _capacity;
}
private:
char* _str;// Store string
size_t _size; // Number of valid characters
size_t _capacity; // The actual space to store valid characters
};
}
void test_string1()
{
LF::string s1("hello");
LF::string s2(s1);
cout << s1.c_str() << endl;
cout << s2.c_str() << endl;
s1[2] = 'P';
cout << s1.c_str() << endl;
cout << s2.c_str() << endl;
}
int main()
{
test_string1();
return 0;
} result :
What is called here is the copy constructor generated by default , Finished is a shallow copy ,s1 The modification will affect s2, And will destruct the same space twice , Report errors .
4.2.string Class common function implementation
1. Capacity expansion
void reserve(size_t n)
{
if (n > _capacity)
{
char* tmp = new char[n + 1];
strcpy(tmp, _str);
delete[] _str;
_str = tmp;
_capacity = n;
}
}2. Expand and initialize
void resize(size_t n, char ch = '\0')
{
if (n < _size)
{
_size = n;
_str[_size] = '\0';
}
else
{
if (n > _capacity)
{
reserve(n);
}
for (size_t i = _size; i < n; ++i)
{
_str[i] = ch;
}
_size = n;
_str[_size] = '\0';
}
}
3. Insert , Delete , data
string& insert(size_t pos, char ch)
{
assert(pos <= _size);
if (_size == _capacity)
{
reserve(_capacity == 0 ? 4 : _capacity * 2);
}
size_t end = _size+1;
while (end > pos)
{
_str[end] = _str[end-1];
--end;
}
_str[pos] = ch;
_size++;
return *this;
}
string& insert(size_t pos, const char* str)
{
assert(pos <= _size);
size_t len = strlen(str);
if (_size + len > _capacity)
{
reserve(_size + len);
}
// Move back len A place
size_t end = _size + len;
while (end > pos+len-1)
{
_str[end] = _str[end -len];
--end;
}
strncpy(_str + pos, str, len);
_size += len;
return *this;
}
string& earse(size_t pos, size_t len = npos)//size_t nops=-1;
{
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;
}
// Reuse
string& operator+=(const char* str)
{
append(str);
return *this;
}
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
void push_back(char ch)
{
//if (_size == _capacity)
//{
// reserve(_capacity == 0 ? 4 : _capacity*2);
// //reserve(_capacity*2);
//}
//_str[_size] = ch;
//++_size;
//_str[_size] = '\0';
insert(_size, ch);
}
void append(const char* str)
{
/*size_t len = _size + strlen(str);
if (len > _capacity)
{
reserve(len);
}
strcpy(_str + _size, str);
_size = len;*/
insert(_size, str);//
}4. lookup
size_t find(char ch, size_t pos = 0)
{
for (; pos < _size; ++pos)
{
if (_str[pos] == ch)
{
return pos;
}
}
return npos;
}
size_t find(const char* str, size_t pos = 0)
{
const char* p = strstr(_str + pos, str);
if (p == nullptr)
{
return npos;
}
else
{
return p - _str;
}
}5. Operator overload
ostream& operator<<(ostream& out, const string& s)
{
for (auto ch : s)
{
out << ch;
}
return out;
}
istream& operator>>(istream& in, string& s)
{
char ch;
in >> ch;
ch = in.get();
while (ch != ' ' && ch != '\n')
{
s += ch;
in >> ch;
ch = in.get();
}
return in;
// Or reduce the cost of capacity expansion
char ch;
ch = in.get();
char buff[128] = {'\0'};
size_t i = 0;
while (ch != ' ' && ch != '\n')
{
buff[i++] = ch;
if (i == 127)
{
s += buff;
memset(buff, '\0', 128);
i = 0;
}
ch = in.get();
}
s += buff;
return in;
}
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 || s1 == s2;
}
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);
}6. structure , copy constructor
Another way to do it
void swap(string& s)
{
std::swap(_str, s._str);
std::swap(_size, s._size);
std::swap(_capacity, s._capacity);
}
// s2(s1)
string(const string& s)
:_str(nullptr)
, _size(0)
, _capacity(0)
{
string tmp(s._str);
swap(tmp);
}
string& operator=(string s)// Value passed
{
swap(s);// Shape parameter s Change will not change s
return *this;
}边栏推荐
- Dual machine hot standby of Huawei firewall (NGFW)
- Unity high version returned low version error
- Configure spectrum navigation for Huawei wireless devices
- Antd form setting array fields
- 性能优化之@Contended减少伪共享
- Daily question brushing record (26)
- A summary of C language pointer
- function/symbol ‘pango_ context_ set_ round_ glyph_ positions‘ not found in library ‘libpango-1.0. so. 0‘x
- cv02-roge矩阵,旋转向量 ,角度
- CodeForces - 587E(线性基+线段树+差分)
猜你喜欢

Leetcode 1252. Number of odd value cells

【PostgreSQL 】PostgreSQL 15对distinct的优化

SPI服务发现机制

466-82(3、146、215)

Unity3d read mpu9250 example source code

Performance optimization @contented to reduce pseudo sharing
![[binomial tree] the power of the button cattle customers must brush questions](/img/c0/254c28c5d94635e817fa6ba0b8483a.png)
[binomial tree] the power of the button cattle customers must brush questions

A fastandrobust convolutionalneuralnetwork-based defect detection model inproductqualitycontrol-閱讀筆記

Leetcode 1304. N different integers with zero and

Introduction of database lock, shared with InnoDB, exclusive lock
随机推荐
SPI service discovery mechanism
SPI服务发现机制
At5147-[agc036d]negative cycle [DP, model conversion]
华为无线设备配置频谱导航
Hot discussion: my husband is 34 years old this year and wants to read a doctoral degree. What should I do in the future to do scientific research?
Introduction to virtualization troubleshooting
pjudge#21652-[PR #4]到底有没有九【数位dp】
mysql show processlist 详解
Keras deep learning practice (14) -- r-cnn target detection from scratch
02-3、指針和引用的區別
Learning outline of the column "MySQL DBA's magic road"
03-1. Inline function, auto keyword, typeID, nullptr
要想组建敏捷团队,这些方法不可少
热议:老公今年已经34周岁想读博,以后做科研,怎么办?
Send blocking, receive blocking
TiDB 内存控制文档
Leetcode 1310. 子数组异或查询
Un modèle de détection par défaut basé sur le réseau neuronal évolutif rapide dans le contrôle de la qualité des produits - lire les notes
[untitled] CV learning 1 conversion
QT -- excellent open source project