C++_string简单源码剖析:string模拟实现

大家好!本文会模拟一个基本的string类,帮助我们更好的理解string的内置函数的实现与规则。

先在.h文件声明每个需要实现的函数,需要实现的成员:

namespace bit
{
	class string
	{
	public:
		//1. 构造函数
		string(const char* tmp= "");
		string(const string& tmp);
		string&operator=(const string& s);
		~string();
		
		//2. 迭代器
		typedef char* iterator;
		typedef const char* const_iterator;
		iterator begin();
		iterator end();
		const_iterator begin() const;
		const_iterator end() const;

		//3. 获取
		size_t size() const;
		char& operator[](size_t pos);
		const char& operator[](size_t pos) const;

		//4. 内存修改
		void reserve(size_t n);

		//5. 插入
		string& operator+=(char ch);
		string& operator+=(const char* str);
		void push_back(char c);
		void append(const char* tmp);
		void insert(int pos, char c);
		void insert(int pos, const char* tmp);

		//6. 删除
		void erase(size_t pos = 0, size_t len = npos);

		//7. 查找
		size_t find(char ch, size_t pos = 0);
		size_t find(const char* str, size_t pos = 0);
		
		//8. 交换swap
		void swap(string& s);

		//9. 截取substr
		string substr(size_t pos = 0, size_t len = npos);

		//10. 比较符号重载
		bool operator<(const string& s) const;
		bool operator>(const string& s) const;
		bool operator<=(const string& s) const;
		bool operator>=(const string& s) const;
		bool operator==(const string& s) const;
		bool operator!=(const string& s) const;
		//11. 清除
		void clear();
	private:
		char* _ptr;
		size_t _capacity;
		size_t _size;

		const static size_t npos = -1;
	};
	//12.流插入与流提取
	istream& operator>> (istream& is, string& str);
	ostream& operator<< (ostream& os, const string& str);
}

备注(重要):npos是 const static修饰的变量,它实际上不在类中,其在.h声明后,必须在.cpp的全局域(如果有命名空间限定则在命名空间中)定义赋值。这里在.h给予一个缺省值也能到达定义的效果,但是仅限整形!!,double类型或者其他的任何类型都不能在声明时给缺省值

接下来在另一个.cpp后缀的文件中一步一步的剖析实现。

注意

  1. 在.h声明的函数的形参如果有缺省值,.cpp去实现的函数的形参是不带缺省值的
  2. 我这边模拟的string是放在命名bit里面的,在.cpp去实现时,也要放在bit内实现(就是把实现的函数全部用命名空间bit包起来)

🚀1.构造与析构函数

//1. 构造函数
		string(const char* tmp= "");
		string(const string& tmp);
		string&operator=(const string& s);
		~string();
  1. string::string(const char* tmp):
string::string(const char* tmp) :
	_size(strlen(tmp))
{
	_ptr = new char[_size + 1];
	_capacity = _size;
	strcpy(_ptr,tmp);
}

备注:其中运用到初始化列表的知识,可以到C++入门 类和对象:深入构造函数,static成员,友元函数这个链接了解了解。


2. string(const string& tmp):

string::string(const string& tmp)
{
	string s(tmp);
	swap(s);
}

备注:这是一个比较流氓的写法,生成一个临时的 s去拷贝tmp,然后直接用swap函数交换s里面的内容,完成了拷贝tmp里的内容,同时s在到了生命周期也自动的将释放之前在_ptr指针指向的空间 (注:这个swap函数是我们实现的string内置的函数,它的实现在后文,作用就是交换private里面的三个成员参数_ptr _capacity _size )

  1. string& operator=(const string& s)
string& string::operator=(const string& s){
	string s(tmp);
	swap(s);
}

备注:赋值重载用的方法与拷贝构造(上一个实现的函数)相同


4. ~string()

string::~string()
{
	delete[] _ptr;
	_capacity =  _size = 0;
}

备注:释放_ptr指向的空间

🚀2.迭代器

typedef char* iterator;
typedef const char* const_iterator;
iterator string::begin()
{
	return _ptr;
}
iterator string::end()
{
	return _ptr+ _size;
}
const_iterator string::begin() const
{
	return _ptr;
}
const_iterator string::end() const
{
	return _ptr+ _size;
}

备注: begin()返回首元素的指针,end()返回尾元素下一个位置的指针,当然也要多实现一个const的版本,以适应const string类型。

🚀3.获取

//3. 获取
		size_t string::size() const{
			return _size;
		}
		size_t string::capacity() const
		{
			return _capacity;
		}
		char& string::operator[](size_t pos){
			return _ptr[pos];
		}
		const char& string::operator[](size_t pos) const{
			return _ptr[pos];
		}
		

备注:其中运用到运算符重载的知识,可以到这个链接了解了解。C++入门 类和对象:深入构造函数,static成员,友元函数

🚀 4.内存修改

//4. 内存修改
void string::reserve(size_t n)
{
	if(n > _capacity)
	{
		iterator tmp = _ptr;
		_ptr = new char[n+1];
		_capacity = n;
		strcpy(ptr, tmp);
		delete[] _tmp;
	}
}

备注:用tmp保存原先_ptr指向的空间,_ptr去开新空间,之后拷贝,再释放tmp。这个函数我们不会太经常使用它,但是其他的内部函数经常使用。

🚀5. 插入

//5. 插入
		void push_back(char c);
		void append(const char* tmp);
		void insert(int pos, char c);
		void insert(int pos, const char* tmp);
		string& operator+=(char ch);
		string& operator+=(const char* str);

不同的插入函数代表不同的职能,可以到这个链接去了解C++入门 string类(第一章):string类对象的构造,string类对象的访问即遍历,string类对象的增与删

push_back

void string::push_back(char c)
{
	if(size() == capacity())
	{
		int new_capacity = _capacity==0? 4: _capacity*2;
		reserve(new_capacity);
	}
	_ptr[_size] = c;
	_size++;
	_ptr[_size] = '\0';
}

备注:先判断是否扩容,再赋值,注意 下标为 _size 位置的是 ‘\0’ ,别忘了在最后补上 ‘\0’


append:

void string::append(const char* tmp)
{
	int len = strlen(tmp);
	if(size()+ len >= capacity())
	{
		reserve(size()+ len);
	}
	strcpy(_ptr+_size,tmp);
	_size+=len;
}

备注:不用考虑’ \0’的问题,tmp内自带一个’\0’

insert:

void  string::insert(int pos, char c)
{
	if(size() == capacity())
	{
		int new_capacity = _capacity==0? 4: _capacity*2;
		reserve(new_capacity);
	}
	int end = size();
	while(end >= pos)
	{
		_ptr[end+1] = _ptr[end];
	}
	_size++;
	_ptr[pos] = c;
}
void  string::insert(int pos, const char* tmp)
{
	int len = strlen(tmp);
	if(size()+ len >= capacity())
	{
		reserve(size()+ len);
	}
	int end = size() +len;
	while(end>= pos+len)
	{
		_prt[end] = _ptr[len-len]
	}
	memcpy(_ptr+pos,tmp,len);
	_size +=len;
}

备注:插入字符串的时,图例:
在这里插入图片描述

且不能使用strcpy了,strcpy会同\0一起拷贝,所以这里用memcpy

operator+=:

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

备注:复用push_back与append

🚀6. 删除

void string::erase(size_t pos , size_t len )
{
	if(pos+len >= size())
	{
		ptr[pos] = '\0';
		_size = pos+1;
	}
	else
	{
		strcpy(_ptr+pos,_ptr+pos+len);
		_size -= len;
	}
}

备注:从pos开始,删除长度大于size的,直接在pos下标赋值’\0’ ; 除此之外,都将_ptr+pos+len后的字符拷贝到_ptr+pos位置

🚀7. 查找

//7. 查找
		size_t find(char ch, size_t pos )
		{
			for(int i = 0;  i< size();i++)
			{
				if(ch == _ptr[i])return i;
			}
			return npos;
		}
		size_t find(const char* str, size_t pos)
		{
			char* p = strstr(_ptr + pos, str);
			return  p - _ptr;
		}

备注:查找字符串是直接复用库里的strstr函数。

🚀8. 交换swap

//8. 交换swap
		void swap(string& s)
		{
			std::swap(s._ptr, _ptr);
			std::swap(s._size, _size);
			std::swap(s._capacity, _capacity);
		}

备注:本质是交换private的三个参数。

🚀9. 截取substr

//9. 截取substr
		string substr(size_t pos, size_t len)
		{
			if(pos+len >= size())
			{
				string tmp(_ptr+pos);
				return tmp;
			}
			else
			{
				string tmp(_ptr+pos);
				tmp[len+1] = '\0';
				tmp._size() = len;
				return tmp;
			}
		}

🚀10. 比较符号重载

//10. 比较符号重载
bool string::operator<(const string& s) const
{
	return strcmp(this->_ptr, s._ptr)<0 ;
}
bool string::operator>(const string& s) const
{
	return strcmp(this->_ptr, s._ptr) > 0;
}

bool string::operator<=(const string& s) const
{
	return strcmp(this->_ptr, s._ptr) <= 0;

}
bool string::operator>=(const string& s) const
{
	return strcmp(this->_ptr, s._ptr) >= 0;
}

bool string::operator==(const string& s) const
{
	return !strcmp(this->_ptr, s._ptr);
}
bool string::operator!=(const string& s) const
{
	return strcmp(this->_ptr, s._ptr);
}

备注:复用的是库里的strcmp函数。一个一个字符比较,不相等就返回结果,字符大小的判断咨询ASCll码

🚀11. 清除

//11. 清除
	void string::clear(){
		_size = 0;
		_ptr[0] = '\0';
	}

备注:clear同样也可以复用erase去实现

🚀12.流插入与流提取

//12.流插入与流提取
	istream& operator>> (istream& is, string& str){
		str.clear();
		char ch = get();
		while(ch != '\0')
		{
			str+=ch;
			get();
		}
		return is;
	}
	ostream& operator<< (ostream& os, const string& str){
		for (size_t i = 0; i < str.size(); i++)
		{
			os << str[i];
		}
		return os;
	}

备注:流插入与流提取不是成员函数,实现在类外。 >>重载用到get函数,取得一个输入的字符并尾插到str,当这个字符是换行’\n’时,就不再获取

全部代码:

//.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <cstring>
#include<string>
using namespace std;
namespace bit
{
	class string
	{
	public:
		//构造函数
		//string();
		string(const char* tmp= "");
		string(const string& tmp);
		string&operator=(const string& s);
		~string();
		
		//迭代器
		typedef char* iterator;
		typedef const char* const_iterator;
		iterator begin();
		iterator end();
		const_iterator begin() const;
		const_iterator end() const;

		//获取
		size_t size() const;
		size_t capacity() const;
		char& operator[](size_t pos);
		const char& operator[](size_t pos) const;

		//内存修改
		void reserve(size_t n);

		//插入
		string& operator+=(char ch);
		string& operator+=(const char* str);
		void push_back(char c);
		void append(const char* tmp);
		void insert(int pos, char c);
		void insert(int pos, const char* tmp);

		//删除
		void erase(size_t pos = 0, size_t len = npos);

		//查找
		size_t find(char ch, size_t pos = 0);
		size_t find(const char* str, size_t pos = 0);
		
		//交换swap
		void swap(string& s);

		//截取substr
		string substr(size_t pos = 0, size_t len = npos);

		//比较符号重载
		bool operator<(const string& s) const;
		bool operator>(const string& s) const;
		bool operator<=(const string& s) const;
		bool operator>=(const string& s) const;
		bool operator==(const string& s) const;
		bool operator!=(const string& s) const;
		//清除
		void clear();
	private:
		char* _ptr;
		size_t _capacity;
		size_t _size;

		const static size_t npos = -1;
	};
	//流插入与流提取
	istream& operator>> (istream& is, string& str);
	ostream& operator<< (ostream& os, const string& str);
}


//.cpp
#include "string.h"

namespace bit
{
	//构造函数
	//string();

	string::string(const char* tmp) :
		_size(strlen(tmp))
	{
		_ptr = new char[_size + 1];
		_capacity = _size;
		strcpy(_ptr,tmp);
	}
	
	string::~string()
	{
		delete[] _ptr;
		_capacity = _size = 0;
	}
	
	string& string::operator=(const string& s)
	{
		//方法1 : 传统方法
		if (this != &s)
		{
			char* tmp = new char[s._capacity + 1];
			strcpy(tmp, s._ptr);
			delete[] _ptr;
			_ptr = tmp;
			_size = s._size;
			_capacity = s._capacity;
		}
		//新派方法,使用swap直接拷贝
		//string tmp_s(s._ptr);
		//this->swap(tmp_s);
		return *this;
	}

	string::string(const string& tmp) 
	{
		//方法1 : 传统方法
		 /*_size = tmp._size  ;
		 _capacity = tmp._capacity;
		 _ptr = new char[_capacity + 1];
		 strcpy(_ptr, tmp._ptr);*/

		//方法2 :新派方法,使用swap直接拷贝
		string tmp_s(tmp._ptr);
		this->swap(tmp_s);
	}

	//迭代器
	string::iterator string::begin()
	{
		return _ptr;
	}
	string::iterator string::end()
	{
		return _ptr+_size;
	}

	string::const_iterator string::begin() const
	{
		return _ptr;
	}
	string::const_iterator string::end() const
	{
		return _ptr + _size;
	}
	//获取
	size_t string::size() const
	{
		return _size;
	}

	size_t string::capacity() const
	{
		return  _capacity;
	}
	char& string::operator[](size_t pos)
	{
		return _ptr[pos];
	}

	const char& string::operator[](size_t pos) const
	{
		return _ptr[pos];
	}
	//内存修改
	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			iterator tmp = _ptr;
			_ptr = new char[n + 1];
			_capacity = n;
			strcpy(_ptr, tmp);
			delete[] tmp;
		}
	}	

	/*void string::print()
	{
		int i = 0;
		while (i != _size)
		{
			cout << _ptr[i] ;
			i++;
		}
	}*/
	
	//插入
	void string::push_back(char c)
	{
		if (_size == _capacity)
		{
			int new_capacity = _capacity == 0 ? 4 : _capacity * 2;
			reserve(new_capacity);
		}
		_ptr[_size] = c;
		_size++;
		_ptr[_size] = '\0';
	}

	void string::append(const char* tmp)
	{
		int len = strlen(tmp);
		if (size() + len >= capacity())
		{
			reserve(size() + len);
		}
		strcpy(_ptr + _size, tmp);
		_size += len;
	}
	void string::insert(int pos, char c)
	{
		if (_size == _capacity)
		{
			int new_capacity = _capacity == 0 ? 4 : _capacity * 2;
			reserve(new_capacity);
		}
		size_t end = _size;
		while ((int)end >= pos)
		{
			_ptr[end + 1] = _ptr[end];
		end--;
		}
		_ptr[pos] = c;
		_size++;
	}
	void string::insert(int pos, const char* tmp)
	{
		int len = strlen(tmp);
		if (_size + len >= _capacity)
		{
			reserve(size() + len);
		}
		
		int end = (int)_size + len;
		while (end >= pos + len)
		{
			_ptr[end] = _ptr[end - len];
			end--;
		}

		memcpy(_ptr + pos, tmp, len);
		_size += len;
	}

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

	//删除
	void string::erase(size_t pos, size_t len)
	{
		if (pos + len >= _size)
		{
			_ptr[pos] = '\0';
			_size = pos;
		}
		else
		{
			strcpy(_ptr + pos, _ptr + pos+len);
			_size -= len;
		}
	}
	//查找
	size_t string::find(char ch, size_t pos )
	{
		for (int i = pos; i < _size; i++)
		{
			if (ch == _ptr[i])
			{
				return i;
			}
		}
		return npos;
	}
	size_t string::find(const char* str, size_t pos )
	{
		char* p = strstr(_ptr + pos, str);
		return  p - _ptr;
	}

	void string::swap(string& s)
	{
		std::swap(s._ptr, _ptr);
		std::swap(s._size, _size);
		std::swap(s._capacity, _capacity);
	}
	string string::substr(size_t pos , size_t len)
	{
		if (pos + len >= _size)
		{
			string tmp(_ptr + pos);
			return  tmp;
		}
		else
		{
			string tmp(_ptr + pos);
			tmp._size = len;
			tmp._ptr[len] = '\0';
			return tmp;
		}
	}
	bool string::operator<(const string& s) const
	{
		return strcmp(this->_ptr, s._ptr)<0 ;
	}
	bool string::operator>(const string& s) const
	{
		return strcmp(this->_ptr, s._ptr) > 0;
	}
	
	bool string::operator<=(const string& s) const
	{
		return strcmp(this->_ptr, s._ptr) <= 0;
	
	}
	bool string::operator>=(const string& s) const
	{
		return strcmp(this->_ptr, s._ptr) >= 0;
	}

	bool string::operator==(const string& s) const
	{
		return !strcmp(this->_ptr, s._ptr);
	}
	bool string::operator!=(const string& s) const
	{
		return strcmp(this->_ptr, s._ptr);
	}
	void string::clear()
	{
		_size = 0;
		_ptr[0] = '\0';
	}
	istream& operator>> (istream& is, string& str)
	{
		str.clear();
		char ch = is.get();
		while ( ch != '\n')
		{
			str += ch;
			ch = is.get();
		}
		return is;
	}
	ostream& operator<< (ostream& os, const string& str)
	{
		for (size_t i = 0; i < str.size(); i++)
		{
			os << str[i];
		}
		return os;
	}

}

本文就到这里,感谢你看到这里!
我知道一些人看文章喜欢静静看,不评论,但是他会点赞,这样的人,帅气低调有内涵,美丽大方很优雅,明人不说暗话,要你手上的一个点赞!

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值