当前位置:网站首页>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 .

原网站

版权声明
本文为[Li Fengxi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207221913297101.html