【C++修炼之路】9. string类的模拟实现

news2025/7/8 17:17:15

在这里插入图片描述
每一个不曾起舞的日子都是对生命的辜负

string类的模拟实现

  • 前言
  • 代码:
    • 1. string.h
    • 2. test.cpp
  • 扩展:内置类型的拷贝构造
  • 总结

前言

本篇文章是衔接上一篇string,进行string的模拟实现,其中包含了众多重载函数,以及一些实现的细节,由于上篇已经知道具体函数的含义,这一篇就以纯代码的方式进行叙述。此外,这篇还对内置类型的知识进行了进一步的扩展。

代码:

1. string.h

#pragma once
#include<iostream>
#include<string.h>
#include<assert.h>

using namespace std;
namespace cfy
{
	class string
	{
	public:
		typedef char* iterator;

		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}
		/*string()
		{
			_str = new char[1];
			_str[0] = '\0';
			_capacity = _size = 0;
		}*/
		string(const char* str = "")
		{
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_size + 1];

			strcpy(_str, str);
		}
		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)//tmp指向随机值会有影响,未初始化会导致野指针的情况,因此在拷贝构造之前要给其初始化为nullptr
			,_size(0)
			,_capacity(0)
		{
			string tmp(s._str); // 是构造函数,因为s._str是一个值,不是一个对象
			//this->swap(tmp);
			swap(tmp);
		}//tmp作为临时变量除了作用域会自动调用析构,因此上面进行了解释。
		
		//s2(s1)
		//拷贝构造的传统写法
		/*string(const string& s)
		{
		
			_str = new char[s._capacity + 1];
			_capacity = s._capacity;
			_size = s._size;

			strcpy(_str, s._str);
		}*/
		// s1 = s3
		/*string& operator=(const string& s)
		{
			if (this != &s)
			{
				char* tmp = new char[s._capacity + 1];
				strcpy(tmp, s._str);

				_size = s.size();
				_capacity = s._capacity;
			}

			return *this;
		}*/
		/*string& operator=(const string& s)
		{
			if (this != &s)
			{
				string tmp(s);
				swap(tmp);
			}
			return *this;
		}*/

		// s1 = s3
		string& operator=(string s)
		{
			swap(s);
			return *this;
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}
		const char* c_str() const
		{
			return _str;
		}
		size_t size() const
		{
			return _size;
		}
		size_t capacity() const 
		{
			return _capacity;
		}
		//普通对象:可读可写
		char& operator[](size_t pos) const
		{
			assert(pos < _size);
			return _str[pos];
		}
		// const对象:只读
		char& operator[](int pos) 
		{
			assert(pos < _size);
			return _str[pos];
		}

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

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

				_size = n;
				_str[_size] = '\0';
			}
			else
			{
				_str[n] = '\0';
				_size = n;
			}
		}
		
		void push_back(char ch)
		{
			if (_size == _capacity)
			{
				size_t newCapacity = _capacity == 0 ? 4 : _capacity * 2;
				reserve(newCapacity);
				_capacity = newCapacity;
			}
			_str[_size++] = ch;
			_str[_size] = '\0';//注意处理末尾
		}

		void append(const char* str)
		{
			size_t len = strlen(str);

			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}

			strcpy(_str + _size, str);
			_size += len;
		}

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

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

		string& insert(size_t pos, char ch)
		{
			assert(pos <= _size);

			if (_size >= _capacity - 1)//改
			{
				size_t newCapacity = _capacity == 0 ? 4 : _capacity * 2;
				reserve(newCapacity);
			}

			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)
		{

			size_t len = strlen(str);

			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}

			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& erase(size_t pos, size_t len = npos)
		{
			assert(pos < _size);

			if (len == npos || pos + len >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				strcpy(_str + pos, _str + pos + len);
				_size -= len;
			}

			return *this;
		}
		size_t find(const char ch, size_t pos = 0) const
		{
			assert(pos < _size);
			while (pos < _size)
			{
				if (_str[pos] == ch)
				{
					return pos;
				}
				++pos;
			}
			return npos;
		}

		size_t find(const char* str, size_t pos = 0) const
		{
			assert(pos < _size);
			const char* ptr = strstr(_str + pos, str);
			if (ptr == nullptr)
			{
				return npos;
			}
			else
			{
				return ptr - _str;
			}

		}
		void clear()
		{
			_size = 0;
			_str[0] = '\0';
		}
	private:
		char* _str;
		size_t _size;
		size_t _capacity;

		const static size_t npos = -1;//只有这个是特例
	};

	ostream& operator<<(ostream& out, const string& s) 
	{
		for (size_t i = 0; i < s.size(); i++)
		{
			out << s[i];
		}
		return out;
	}
	istream& operator>>(istream& in, string& s)
	{
		s.clear();
		/*char ch = in.get();
		while (ch != ' ' && ch != '\n')
		{
			s += ch;
			ch = in.get();
		}
		return in;*/

		char buff[128] = { '\0' };//防止扩容代价大,通过buff暂时储存,一段一段进
		size_t i = 0;
		char ch = in.get();
		while (ch != ' ' && ch != '\n')
		{
			if (i < 127)
			{
				buff[i++] = ch;
			}
			else
			{
				s += buff;
				i = 0;
				buff[i++] = ch;
			}
			ch = in.get();
		}
		if (i > 0)
		{
			buff[i] = '\0';
			s += buff;
		}
	}
	void test_string1()
	{
		string s1("hello world");
		cout << s1.c_str() << endl;

		for (size_t i = 0; i < s1.size(); i++)
		{
			s1[i]++;
		}
		cout << s1.c_str() << endl;


		string::iterator it1 = s1.begin();
		while (it1 != s1.end())
		{
			(*it1)--;
			it1++;
		}
		cout << s1.c_str() << endl;

		for (auto ch : s1)//底层是调用迭代器iterator,官方库就是这样
		{
			cout << ch << " ";
		}
		cout << endl;

		s1.push_back('!');
		s1.push_back('!');
		s1.push_back('!');
		cout << s1.c_str() << endl;
	}

	void test_string2()
	{
		string s1("hello");
		s1 += ' ';
		s1 += '!';
		s1 += '!';
		s1 += "happy";
		cout << s1.c_str() << endl;

		string s2;

		s2 += 'x';
	
		cout << s2.c_str() << endl;
	}

	void test_string3()
	{
		string s1("hello world");

		s1.insert(6, " cfy ");
		cout << s1.c_str() << endl;
		s1.insert(0, "");
		cout << s1.c_str() << endl;
	}

	void test_string4()
	{
		string s1("hello hello world");
		s1.erase(0, 6);
		cout << s1.c_str() << endl;
	}

	void test_string5()
	{
		string s1("hello hello world");
		s1.resize(25, 'x');
		cout << s1.c_str() << endl;
	}

	void test_string6()
	{
		string s1("hello world");
		
		cout << s1 << endl;
		cout << s1.c_str() << endl;

		s1.insert(5, '\0');
		cout << s1.size() << endl;
		cout << s1.capacity() << endl;
		cout << s1 << endl;
		cout << s1.c_str() << endl;

		//string s2;
		cout << s1 << endl;
		cin >> s1;
		cout << s1 << endl;

	}
	void test_string7()
	{
		string s1("hello world");
		string s2(s1); // 默认的拷贝构造是浅拷贝,指针指向同一个位置,对开辟的空间的析构会析构多次,导致错误。
		cout << s2 << endl;
	}
	void test_string8()
	{
		string s1("hello");
		cout << s1 << endl;

		string s2("world");
		cout << s2 << endl;

		s1.swap(s2);
		cout << "s1:" << s1 << endl;
		cout << "s2:" << s2 << endl;
	}
}

2. test.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include"string.h"


int main()
{
	cfy::test_string8();

	/*int i(10);
	cout << i << endl;
	int j = int();
	cout << j;*/
	return 0;
}

扩展:内置类型的拷贝构造

image-20221116134330292

对于C++来说,我们知道其具有默认的拷贝构造函数,这是对自定义的类实现的,但由于C++含有泛型模板template<T>,我们发现其也可以作为类,因此也具有构造和拷贝构造、析构等默认成员函数,因此这也让内置类型支持了拷贝构造,因为我们可以将T替换成相应的内置类型时间比如我们耳熟能详的int、char、double,那我们就来看一下具体做法:

#inclue<iostream>
using namespace std;
int main()
{
	int i(10);
	cout << i << endl;
	int j = int();
	cout << j;
	return 0;
}

image-20221116135507669

#inclue<iostream>
using namespace std;
int main()
{
	double d(10.0);
	double j = double();
	cout << d << " " << j << endl;
	char a('A');
	cout << a << endl;
	return 0;
}

image-20221116135750845

因此,由于C++有泛型模板可以进行这样的操作,但对于C而言,这样的操作就是错误的了。

image-20221116140003866

总结

此篇文章不长,大多通过直接展示代码的形式介绍了string内部函数的模拟实现,此外又添加了template的扩展知识,希望对你有所帮助。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/9051.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

pytest中allure特性

一、allure.step allure报告最重要的一点是&#xff0c;它允许对每个测试用例进行非常详细的步骤说明 通过 allure.step() 装饰器&#xff0c;可以让测试用例在allure报告中显示更详细的测试过程 step() 只有一个参数&#xff0c;就是title&#xff0c;你传什么&#xff0c;在…

Linux------网络基础1

文章目录计算机网络的发展历程网络协议计算机网络分层体系结构局域网通信的原理IP地址和 MAC地址的区别计算机网络的发展历程 简单的了解一下就行&#xff0c;图就不提供了。 1&#xff0c;最开始&#xff0c;计算机之间是相互独立的&#xff0c;不能沟通交流。 2&#xff0c;…

第02章_MySQL的数据目录

第02章_MySQL的数据目录1. MySQL8的主要目录结构1.1 数据库文件的存放路径1.2 相关命令目录1.3 配置文件目录2. 数据库和文件系统的关系2.1 查看默认数据库2.2 数据库在文件系统中的表示2.3 表在文件系统中的表示1. MySQL8的主要目录结构 [rootatguigu01 ~]# find / -name mys…

React中的useEffect(副作用)

目录 useEffect(副作用)介绍 useEffect(副作用)各种写法的调用时刻 1.写法一&#xff1a;没有依赖项时 父组件给子组件传值&#xff1a; 2.写法二:依赖项中有监听的值时 3.写法三&#xff1a;依赖项为空数组时 4.写法4&#xff1a;清除副作用写法(假如副作用是一个定时器,…

【C++】string类的模拟实现

文章目录一、string类的构造、拷贝构造、赋值重载以及析构1.构造函数2.拷贝构造3.swap问题4.赋值重载5.析构函数二、常用接口1.c_str2.[]3.迭代器和范围for4.size和capacity三、插入1.reserve和resize2.push_back3.append4.5.insert四、删除1.erase2.clear五、查找1.find六、运…

Nginx

What is Nginx&#xff1f; Nginx 同 Apache 一样都是一种 Web 服务器。基于 REST 架构风格&#xff0c;以统一资源描述符&#xff08;Uniform Resources Identifier&#xff09;URI 或者统一资源定位符&#xff08;Uniform Resources Locator&#xff09;URL 作为沟通依据&…

基于51单片机的多功能时钟温度计proteus仿真原理图

本系统是由AT89S52单片机为控制核心&#xff0c;具有在线编程功能&#xff0c;低功耗&#xff0c;能在3V超低压环境中工作&#xff1b;时钟电路由内部时钟电路外接晶振提供&#xff0c;它是一种高性能、低功耗、带RAM的可随时调整时钟电路&#xff0c;工作电压为3V&#xff5e;…

数据中台与大数据、数据仓库、数据湖、BI的区别

一、什么是数据中台 数据中台是一种将企业沉睡的数据变成数据资产&#xff0c;持续使用数据、产生智能、为业务服务&#xff0c;从而实现数据价值变现的系统和机制。通过数据中台提供的方法和运行机制&#xff0c;形成汇聚整合、提纯加工、建模处理、算法学习&#xff0c;并以…

电源管理ISL95869HRTZ、ISL95808HRZ概述、规格和应用

ISL95869完全符合英特尔IMVP9规范&#xff0c;并为处理器的主输入轨道电源提供了完整的解决方案。它提供了一个电压调节器(VR)与两个集成和一个外部门驱动器。VR可以配置为3-&#xff0c;2-或1-相位&#xff0c;提供最大的灵活性。虚拟现实采用串行控制总线SVID (serial contro…

es环境搭建

1.es与es-head的搭建 1.1 es7.6.2 每个es都是自成一个集群&#xff0c;不同于solar还需要zk来搭建集群 1.1.1 下载安装 https://www.elastic.co/cn/downloads/past-releases/elasticsearch-7-6-2 因为占用内存实在是太大了&#xff0c;我在服务器上装了运行不起来&#xff…

Flameshot源码编译方法

一、简介 Flameshot是一款功能强大但易于使用的屏幕截图软件&#xff0c;中文名称火焰截图。Flameshot 简单易用并有一个CLI版本&#xff0c;所以你也可以从命令行来进行截图。Flameshot 是一个Linux发行版中完全免费且开源的截图工具。 二、在线安装 在线安装方法很简单&…

java基于web的自行车租赁系统ssh

目 录 摘 要 I Abstract II 第1章 绪论 1 1.1 课题背景 1 1.2 课题研究的意义 1 1.3 课题的目标 2 1.4 研究内容与章节安排 2 第2章 可行性分析 3 2.1 经济可行性 3 2.2 技术可行性 3 2.3 操作可行性 4 2.4法律可行性 4 2.5业务流程分析…

win10实现nfs文件共享II

文章目录&#xff08;一&#xff09;在服务器A设置共享目录&#xff08;二&#xff09;在客户端B安装nfs,挂载目录&#xff08;一&#xff09;在服务器A设置共享目录 步骤1&#xff1a;在D盘新建目录“nfs”,将其目录设置为共享目录。 步骤2&#xff1a;点击权限&#xff0c;设…

税票贷产品的准入与额度判断有哪些逻辑

近两周&#xff0c;番茄风控的课程中&#xff0c;涉及的税票贷产品课程干货满满。 今天我们再跟大家讲一下关于税票贷中风控的核心准入策略与额度判断有哪些逻辑是需要关注的&#xff1f; 先来说下税务的数据&#xff0c;然后再来讲下发票类型的数据。 一.关于税务的风控准入策…

PCB Layout爬电距离、电气间隙如何确定-安规

PCB Layout爬电距离、电气间隙如何确定 爬电距离&#xff1a;沿绝缘表面测得的两个导电零部件之间或导电零部件与设备防护界面之间的最短路径。 电气间隙&#xff1a;在两个导电零部件之间或导电零部件与设备防护界面之间测得的最短空间距离。即在保证电气性能稳定和安全的情况…

Redis真没那么难,这份大佬实战笔记也太可了,吹爆

Redis的技术全景 Redis一个开源的基于键值对&#xff08;Key-Value&#xff09;NoSQL数据库。使用ANSI C语言编写、支持网络、基于内存但支持持久化。性能优秀&#xff0c;并提供多种语言的API。 我们要首先理解一点&#xff0c;我们把Redis称为KV数据库&#xff0c;键值对数据…

图解LeetCode——775. 全局倒置与局部倒置(难度:中等)

一、题目 给你一个长度为 n 的整数数组 nums &#xff0c;表示由范围 [0, n - 1] 内所有整数组成的一个排列。 全局倒置 的数目等于满足下述条件不同下标对 (i, j) 的数目&#xff1a; 0 < i < j < nnums[i] > nums[j]局部倒置 的数目等于满足下述条件的下标 i 的…

【Opencv实战】识别水果的软件叫什么?一款超好用的识别软件分享,一秒鉴定(真是活~久~见~啊)

导语 Hello&#xff0c;大家好呀&#xff01;我是木木子吖&#xff5e; 一个集美貌幽默风趣善良可爱并努力码代码的程序媛一枚。 听说关注我的人会一夜暴富发大财哦——不信你试试&#xff01; 所有文章完整的素材源码都在&#x1f447;&#x1f447; 粉丝白嫖源码福利&…

redis(二)

一、短信登录 1.1导入黑马点评项目 导入黑马点评项目 首先&#xff0c;导入课前资料提供的SQL文件 其中的表有&#xff1a; tb_user&#xff1a;用户表tb_user_info&#xff1a;用户详情表tb_shop&#xff1a;商户信息表tb_shop_type&#xff1a;商户类型表tb_blog&#xf…

Golang入门(1)—— helloworld 初体验

没有多少雄心壮志&#xff0c;就是想在B站上跟一个视频&#xff0c;写一个helloworld 。 还是老配方&#xff0c;还是IDEA&#xff0c;简单的下载了一个go插件之后&#xff0c;就可以new go文件了。然后根据提示下载了一个最新的go版本&#xff0c;设置好环境变量。写了如下&am…