当前位置:网站首页>Simulation Implementation of string

Simulation Implementation of string

2022-06-22 15:57:00 Stock god.

String Required members

string This type uses 4 Member variables and several member functions are encapsulated .
The member variables are :

  • char* _str: This member variable is used to point to the opened string
  • size_t _size: Indicates the size of the string
  • size_t _capacity: indicate string The space occupied , To work with size This member distinguishes ,_size Indicates the actual size of the string , and _capacity Indicates the amount of space occupied ,
    _capacity >= _size
  • static const size_t npos: yes string A built-in member variable , The value is -1, This variable is static Of , It belongs to the whole class

string Class constructor

1、_capacity+1 Because _str Is pointing to the space of the string , And the string has "\0", As an end sign , therefore _str The space pointed to should be one byte larger .

		string(const char* str = "")
			:_size(strlen(str)),
			_capacity(_size)// no need +1
		{
    
			_str = new char[_capacity+1];// Only here +1
			strcpy(_str, str);
		}

string Destructor of class

Destructor needs to release _str Point to space , And will _size and _capacity Set as 0

		~string()
		{
    
			delete[] _str;
			_str = nullptr;
			_size = 0;
			_capacity = 0;
		}

Copy structure

1、 Use the constructor to construct a temporary object tmp, Reuse swap Function exchange tmp Content of

		void swap(string& s)
		{
    
			std::swap(_str, s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}
		// Modern writing of deep copy 
		string(const string& s)
			:_str(nullptr),// This must be initialized to a null pointer . If null pointer is not initialized , It's a random value , In exchange for tmp after ,tmp Out of scope , Destroy call destruct , Destroy the space of random values , There is a wild pointer problem 
			_size(0),
			_capacity(0)
		{
    
			string tmp(s._str);//tmp Is a temporary object , Out of scope destroy , because tmp The content and content of this Swap , So there is no memory to destroy .s._str It's one by one char*, And this char* Refers to parameters s String , This sentence is equivalent to string tmp=(” A string “), This sentence calls string Constructor for 
			swap(tmp);
		}

Assignment operator overload

1、 Because it is value transfer and parameter transfer , So the copy construct is called , Construct a temporary object tmp, Call again swap Function exchange tmp The content of . Out of scope ,tmp This object will call the destructor to destroy .

		string& operator=(string tmp)
		{
    
			swap(tmp);
			return *this;
		}

c_str()、size()、[] Operator overloading

c_str(): It's used to return to c Interface of formal string
size(): Returns the size or length of a string
operator[]: This interface has a normal version and const Version of

		const char* c_str() const// Don't worry about why const char* ,c_str The return is c Formal string , and c This is the type of string 
		{
    
			return _str;
		}

		size_t size() const // This const This is to enable ordinary objects to call ,const Objects can also call , If you don't write , You have to const Object to write another function .
		{
    
			return _size;
		}

		char& operator[](size_t pos)
		{
    
			assert(pos < _size);// Forget to write this sentence 
			return *(_str + pos);
			//return _str[pos];

		}

		const char& operator[](size_t pos)const// the last one const modification this The pointer , Composition function overload ( The return value does not constitute a function overload ), Give Way const Object call 
		{
    
			assert(pos < _size);
			return *(_str + pos);
		}

reserve(): Expansion function

		void reserve(size_t n)
		{
    
			if (n > _capacity)
			{
    
				char* tmp = new char[n + 1];
				strcpy(tmp,_str);
				delete[] _str;
				_str = tmp;
				_capacity = n;
			}
		}

resize(): Set the size and initialize

Set size n Yes 3 Medium condition :1、n<=_size 2、n>_size, however n<=capacity 3、n>capacity
The default initialization character is 0
When setting the n To be less than _size when , Directly subscript n Output setting "\0", As the end of a string , There is no need to reduce the space .
When setting the n Be greater than _capacity, Need to expand

		void resize(size_t n, char ch = '\0')
		{
    
			if (n <= _size)
			{
    
				_str[n] = '\0';
				_size = n;
			}
			else
			{
    
				if (n > _capacity)
				{
    
					reserve(n);
				}
				memset(_str+_size,ch,n-_size);
				_size = n;
				_str[_size] = '\0';
				
				
			}
		}

insert(): stay pos Insert a character or string at the subscript

Insert a character : When the length of the string equals the capacity , Need to expand ; Then you need to move the data , stay pos To insert the character ch; Subscript end The point is \0 Next to

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[end] = ch;
			++_size;

			return *this;

		}

Insert a string :

string& insert(size_t pos, const char* s)
		{
    
			assert(pos <= _size);
			size_t len = strlen(s);
			if (_size + len > _capacity)
			{
    
				reserve(_size + len);
			}
			size_t end = _size + len;
			while (end >= pos + len)
			{
    
				_str[end ] = _str[end-len];
				end--;
			}
			strncpy(_str+pos, s,len);//strncpy There is no need to duplicate \0;
			_size += len;
			return *this;
		}

erase: from pos Position start , Delete len A string of length

When the deleted length is npos or pos+len When the length of is greater than the length of the string , Description to delete pos Location ( Include pos Location ) All the following strings .
If it is not , You need to _str + pos + len The following string under position is copied to pos Under the position .

        //erase Will change _size, But it won't change _capacity
		string& erase(size_t pos = 0, size_t len = npos)
		{
    
			assert(pos < _size);
			if (len == npos || pos + len >= _size)
			{
    
				_str[pos] = '\0';
				_size = pos;// Don't think , When this is the case , The length of the description string is pos individual 
				
			}
			else
			{
    
				strcpy(_str + pos, _str + pos + len);//strcpy( Purpose , Source )
				_size -= len;
			}
			return *this;
		}

clear(): Clear all strings

		void clear()
		{
    
			_str[0] = '\0';
			_size = 0;
		}

push_back(): Trailing character

		void push_back( char ch)//ch no need const Modification of , because ch It's not quoting ( Because if it is a quotation , The character has... In the constant field const Properties of ), The value copy is passed , no need const receive 
		{
    
			 Method 1
			//if (_size == _capacity)
			//{
    
			// reserve(_capacity == 0 ? 4 : _capacity * 2);

			//}
			//_str[_size] = ch;
			//++_size;
			//_str[_size] = '\0';

			// Method 2
			insert(_size , ch);
		}

append(): Trailing string

		void append(const char* str)
		{
    
			 Method 1
			//size_t len = strlen(str);
			//if (_size+len > _capacity)
			//{
    
			// reserve(_size + len);
			//}
			//strcpy(_str + _size, str);
			//_size += len;

			// Method 2
			insert(_size, str);
		}

Operator overloading +=:+= A character or a string

		string& operator+=(char ch)
		{
    
			push_back(ch);
			return *this;
		}
		string& operator+=(const char* str)
		{
    
			append(str);
			return *this;
		}

find(): Find a character or string , Found return subscript , No return found npos

npos It's a built-in static Member variables of , Value to -1; If function returns -1 Indicates that... Was not found

		size_t find(char ch)
		{
    
			for (size_t i = 0; i < _size; ++i)
			{
    
				if (_str[i] == ch)
				{
    
					return i;
				}
			}
			return npos;
		}
		
		size_t find(const char* s,size_t pos=0)
		{
    
			const char* ptr = strstr(_str + pos, s);//strstr Is a string comparison function 
			
			if (ptr == nullptr)
			{
    
				return npos;
			}
			else
			{
    
				return ptr - _str;// The return is the subscript 
			}
		}

iterator

string The essence of an iterator is a char Pointer to type , Is a public member variable ( Public is used outside the class )

		typedef char* iterator;
		typedef const char* const_iterator;

		iterator begin()// Returns the beginning of a string 
		{
    
			return _str;
		}
		iterator end()// Returns the end of a string 
		{
    
			return _str + _size;
		}
		const_iterator begin()const
		{
    
			return _str;
		}
		const_iterator end()const
		{
    
			return _str + _size;
		}

Operator overloading ==、 <= 、<、> 、>=、!=

bool operator<(const string& s1, const string& s2)
	{
    
		 Method 1
		//size_t i1 = 0, i2 = 0;
		//while (i1 < s1.size() && i2 < s2.size())
		//{
    
		// if (s1[i1] < s2[i2])
		// {
    
		// return true;
		// }
		// else if(s1[i1] > s2[i2])
		// {
    
		// return false;
		// }
		// else
		// {
    
		// ++i1;
		// ++i2;
		// }
		// 
		//}
		//return i2 < s2.size() ? true : false;

		// Method 2
		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) && !(s1 == s2);
		//return !(s1 <= s2); The teacher's method 
	}

	bool operator>=(const string& s1, const string& s2)
	{
    
		return s1 > s2 || s1 == s2;
		//return !(s1 < s2); The teacher's method 
	}

	bool operator!=(const string& s1, const string& s2)
	{
    
		return !(s1 == s2);
	}

Operator overloading <<: Output string type

	ostream& operator<<(ostream& out, const string& s)
	{
    
		 Method 1
		//for (auto ch : s)
		//{
    
		// out << ch;
		//}
		for (size_t i = 0; i < s.size(); ++i)
		{
    
			out << s[i];
		}

		//out << s.c_str(); //  You can't write that , It can be used in most cases . With this line of code , encounter \0 Stop printing , When 
							// Some strings have \0 when , The following characters cannot be printed . The above code is based on string Of 
							//_size To print the string .
		return out;// This type is returned so that multiple strings can be output consecutively 
	}

Operator overloading >>: towards string Type object input string data

call c.clear(): It's for emptying s Because of the data in . For example, when s There are strings , If you call this operator again at this time to overload the function , We will insert the string we entered after the original string .

	istream& operator>>(istream& in,  string& s)
	{
    
		
		s.clear();//test6 Have a show , To add clean Why .
		char ch = in.get();//get() and getchar() almost ,get yes istream The inside of the class 
		while (ch != ' ' || ch != '\n')
		{
    
			s += ch;
			ch = in.get();
		}
		return in;
	}
原网站

版权声明
本文为[Stock god.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221434312039.html