STL简介&&string的使用及其模拟实现

一、STL简介

1.什么是STL

STL(standard template libaray-标准模板库):是C++标准库的重要组成部分,不仅是一个可复用的组件库,而且是一个包罗数据结构与算法的软件框架。

2.STL的版本

  • 原始版本

    Alexander Stepanov、Meng Lee 在惠普实验室完成的原始版本,本着开源精神,他们声明允许任何人任意运用、拷贝、修改、传播、商业使用这些代码,无需付费。唯一的条件就是也需要向原始版本一样做开源使用。 HP 版本–所有STL实现版本的始祖

  • P. J.版本

    由P. J. Plauger开发,继承自HP版本,被Windows Visual C++采用,不能公开或修改,缺陷:可读性比较低,符号命名比较怪异

  • RW版本

    由Rouge Wage公司开发,继承自HP版本,被C+ + Builder 采用,不能公开或修改,可读性一般

  • SGI版本

    由Silicon Graphics Computer Systems,Inc公司开发,继承自HP版 本。被GCC(Linux)采用,可移植性好,可公开、修改甚至贩卖,从命名风格和编程 风格上看,阅读性非常高。

3.STL的六大组件

STL由容器,配接器,迭代器,空间配置器,算法,仿函数组成,具体内容如下:

在这里插入图片描述

4.STL的重要性

网上有句话说:“不懂STL,不要说你会C++”。STL是C++中的优秀作品,有了它的陪伴,许多底层的数据结构以及算法都不需要自己重新造轮子,站在前人的肩膀上,健步如飞的快速开发,我们可以直接使用,这样就大大提高了开发的效率,因此,STL在笔试,面试是一个被重点考察的对象并且在我们以后的工作中都十分重要

5.如何学习STL

我们可以借助在线网站进行辅助学习:cplusplus.com-the C++Reasoures Networkcppreference.com,相比较与C++官网 cppreference来说,我更推荐大家使用 cplusplus,因为cplusplus更适合初学者,我们可以在上面查询任何函数接口,函数参数等等,并且C语言的相关函数等也可以使用这个网站进行查询,但是cplusplus更新之后需要注册才能进行搜索相关函数等,而注册可能不成功,我们可以点击右上角的"Legacy version"切回到旧版,个人认为旧版比新版更好一些。

在这里插入图片描述

二、标准库中的string类

1.string类

C语言中,字符串是以’\0’结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问

基于上面这些原因,C++标准库提供了string类,string类中提供了各种函数接口,比如类的六个默认成员函数,以及字符串的插入删除,运算符重载等等,我们就可以用string来实例化出具体的对象,然后对字符串进行各种操作。我们需要注意的是,严格来说,string不属于STL,因为string出现的时间比STL早,但是呢,string的各种接口和STL中其他容器的接口非常相似,所以我们也可以把string当做STL的一种。

string类的文档介绍

1.字符串是表示字符序列的类

2.标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。

3.string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信息,请参阅basic_string)。

4.string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。

5.注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作

总结:

1.string是表示字符串的字符串类

2.该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。

3.string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;

4.不能操作多字节或者变长字符的序列。

在使用string类时,必须包含#include头文件以using namespace std;

2.string类的常用接口说明

2.1string类对象的常见构造

string提供了多种构造函数,我们只需要掌握几种常用的即可,其余的需要时我们查询文档即可:

在这里插入图片描述

constructor函数名称 功能说明
string() (重点) 构造空的string类对象,即空字符串
string(const char* s) (重点) 用C-string来构造string类对象
string(size_t n, char c) string类对象中包含n个字符c
string(const string&s) (重点) 拷贝构造函数

举例说明:

void test_string1()
{
    
    
	string s1;
	cout << s1 << endl;

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

	string s3(3, 'a');
	cout << s3 << endl;
	string s4(s3);
	cout << s4 << endl;
}
int main()
{
    
    
	test_string1();
	return 0;
}

在这里插入图片描述

2.2string类对象的容量操作

在这里插入图片描述

函数名称 功能说明
size(重点) 返回字符串有效字符长度
length 返回字符串有效字符长度
capacity 返回空间总大小
empty(重点) 检测字符串释放为空串,是返回true,否则返回false
clear(重点) 清空有效字符
reserve(重点) 为字符串预留空间
resize(重点) 将有效字符的个数该成n个,多出的空间用字符c填充

resize

resize函数是用来调整字符串的大小,一共有3种情况:

1.n小于原字符串的size值,此时就会删除数据,把原字符串的size减小到n,但capacity不改变

2.n大于原字符串的size,但小于capacity,此时会将size后面的空间全部置为字符c,没有传参则置为’\0’

3.n大于原字符串的capacity,此时会将原字符串进行扩容,将原字符串的内容拷贝到新的空间中,并把size后面的空间置为字符c,没有传参则置为’\0’

在这里插入图片描述

void test_resize()
{
    
    
	string s1("hello world");
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl << endl;

	s1.resize(5);
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl << endl;

	s1.resize(15, '!');
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
}
int main()
{
    
    
	test_resize();
	return 0;
}

在这里插入图片描述

reserve

reserve函数用来扩容相当与C语言的realloc函数,它分为两种情况:

1.n大于原字符串的capacity,此时reserve会将capacity扩容到n

2.n小于原字符串的capacity,此时标准并没有规定是否要缩容(VS下不缩容)

以上两种情况多不会改变字符串的长度

在这里插入图片描述

void test_reserve()
{
    
    
	string s1("hello world");
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl << endl;

	s1.reserve(20);
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl << endl;
	
	s1.reserve(3);
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
}
int main()
{
    
    
	test_reserve();
	return 0;
}

在这里插入图片描述

clear

clear函数用来情况字符串,将size置为0,但是capacity是否会改变,标准未定义

在这里插入图片描述

void test_clear()
{
    
    
	string s1("hello world");
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl << endl;

	s1.clear();
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl << endl;
}
int main()
{
    
    
	test_clear();
	return 0;
}

在这里插入图片描述

【总结】

1.size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()

2.clear()只是将string中有效字符清空,不改变底层空间大小

3.resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变

4.reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小

2.3string类对象的访问及遍历操作

函数名称 功能说明
operator[](重点) 返回pos位置的字符,const string类对象调用
begin+end 正向迭代器,begin获取一个字符的迭代器+ end获取最后一个字符下一个位置的迭代器
rbegin+rend 反向迭代器,rbegin获取一个字符的迭代器+ rend获取最后一个字符下一个位置的迭代器
范围for C++11支持更简洁的范围for的新遍历方式

对于遍历字符串,C++提供了三种方式:1.下标+[] 2.迭代器遍历 3.范围for 对于迭代器,我们可以把它当做指针来理解,但是并不是所有的迭代器都是通过指针来实现的,而范围for是迭代器的一个外壳,在调用的使用依然调用的是迭代器

在这里插入图片描述

void test_iterator()
{
    
    
	string s1("123456");
	// 下标+[]遍历
	for (size_t i = 0; i < s1.size(); i++)
	{
    
    
		cout << s1[i];
	}
	cout << endl;

	//迭代器遍历
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
    
    
		cout << *it;
		it++;
	}
	cout << endl;
	
	// 范围for遍历
	for (auto ch : s1)
	{
    
    
		cout << ch;
	}
	cout << endl;

	// 反向迭代器,反向遍历
	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
    
    
		cout << *rit;
		rit++;
	}
	cout << endl;
}
int main()
{
    
    
	test_iterator();
	return 0;
}

在这里插入图片描述

【注意】为了使const对象也可以调用,每个迭代器都设计了const版本

在这里插入图片描述

在这里插入图片描述

2.4string类对象的修改操作

string提供了一些用来修改字符串的函数:

在这里插入图片描述

函数名称 功能说明
push_back 在字符串后尾插字符c
append(重点) 在字符串后追加一个字符串
operator+=(重点) 在字符串后追加字符串str
c_str(重点) 返回C格式字符串
find+nops(重点) 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
rfind 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
substr 在str中从pos位置开始,截取n个字符,然后将其返回

operator+=

operator+=是运算符重载的一种,用于对字符串进行尾插数据,支持尾插一个字符,一个字符数组,一个字符串或者一个字符串对象:

在这里插入图片描述

void test_operator()
{
    
    
	string s1("hello");
	string s2("world");
	s1 += s2;
	cout << s1 << endl;
	s1 += '!';
	cout << s1 << endl;
	s1 += " hello";
	cout << s1 << endl;
}
int main()
{
    
    
	test_operator();
	return 0;
}

在这里插入图片描述

append

append和operator的功能相似,都是在字符串尾部插入数据:

在这里插入图片描述

void test_append()
{
    
    
	string s1("hello");
	string s2("world");
	string s3("123456");
	s1.append(s2);
	cout << s1 << endl;
	s1.append("!!!");
	cout << s1 << endl;
	s1.append(s3, 2, 5);
	cout << s1 << endl;
	s1.append(5, 'a');
	cout << s1 << endl;
}
int main()
{
    
    
	test_append();
	return 0;
}

在这里插入图片描述

insert

insert函数用于向字符串的pos处插入数据

在这里插入图片描述

void test_insert()
{
    
    
	string s1("hello");
	string s2("world");
	s1.insert(5," ");
	cout << s1 << endl;
	s1.insert(6, s2);
	cout << s1 << endl;
	s1.insert(11, "!!!");
	cout << s1 << endl;
}
int main()
{
    
    
	test_insert();
	return 0;
}

在这里插入图片描述

erase

erase用来从pos位置删除n个字符,如果n==npos则删除整个字符串,npos的值为-1,但是npos为无符号数,所以npos其实是无符号整形的最大值,所以没有传递参数的时候默认将字符串删完

在这里插入图片描述

void test_erase()
{
    
    
	string s1("hello world");
	s1.erase(6, 5);
	cout << s1 << endl;
	s1.erase(0);
	cout << s1 << endl;
}
int main()
{
    
    
	test_erase();
	return 0;
}

在这里插入图片描述

c_str

在某些场景下只支持C形式的字符串,即对字符数组进行操作,比如网络传输,fopen等等,我们不能直接使用C++提供的string对象进行操作,所以C++提供了c_str,用于返回C形式的字符串

在这里插入图片描述

void test_c_str()
{
    
    
	string s1("hello world");
	const char* str = s1.c_str();
	printf("%s\n", str);
	cout << str << endl;
}
int main()
{
    
    
	test_c_str();
	return 0;
}

在这里插入图片描述

swap

swap函数用于交换两个字符串,包括指向的字符数组,有效数据个数和容量大小

在这里插入图片描述

void test_swap()
{
    
    
	string s1("123456");
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl << endl;

	string s2("abcdefgh");
	cout << s2 << endl;
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s1.swap(s2);
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl << endl;
}
int main()
{
    
    
	test_swap();
	return 0;
}

在这里插入图片描述

substr

substr函数可以将string中从pos位置开始往后的n个字符构造成一个新的string对象并返回

在这里插入图片描述

void test_substr()
{
    
    
	string s1("hello world!!");
	cout << s1.substr(0, 5) << endl;
	cout << s1.substr(6, 5) << endl;
	cout << s1.substr(11, 2) << endl;
}
int main()
{
    
    
	test_substr();
	return 0;
}

在这里插入图片描述

find

find用于返回一个字符或者一个字符数组或一个string对象,在string中首次出现的位置,如果找不到就返回npos

在这里插入图片描述

void test_find()
{
    
    
	string s1("ababbcbccbab");
	string s2("bab");
	cout << s1.find(s2) << endl;
	cout << s1.find('c') << endl;
	cout << s1.find('c', 10) << endl;
}
int main()
{
    
    
	test_find();
	return 0;
}

在这里插入图片描述

rfind

find函数是默认从起始位置开始从前往后找,而rfind函数默认从倒数第二个位置从后往前找

在这里插入图片描述

在这里插入图片描述

find_first_of

find_first_of函数用于返回string中寻找与字符/字符数组/string中任意一个字符匹配的元素的位置

在这里插入图片描述

在这里插入图片描述

【总结】

1.在string尾部追加字符时,s.push_back© / s.append(1, c) / s += 'c’三种的实现方式差不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串

2.对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好

2.5string类非成员函数

函数 功能说明
operator+ 尽量少用,因为传值返回,导致深拷贝效率低
operator>>(重点) 输入运算符重载
operator<<(重点) 输出运算符重载
getline(重点) 获取一行字符串
relational operators(重点) 大小比较

getline

C++中cin和C语言中的scanf函数都是以空格、换行、Tab作为不同数据之间的分隔符,即遇到他们这些符号就会停止读取数据

void test()
{
    
    
	string s1;
	string s2;
	cin >> s1;
	cout << s1 << endl;
	cin >> s2;
	cout << s2 << endl;
}
int main()
{
    
    
	test();
	return 0;
}

在这里插入图片描述

上面的代码中遇到空格就结束读取,下一个变量继续从缓冲区继续读取数据

C语言提供了gets函数来读取一行字符,C++则是提供了getline函数来读取一行字符,并且我们还可以自己设置结束标志符

在这里插入图片描述

void test_getline()
{
    
    
	string s1;
	string s2;
	getline(cin, s1);  //默认遇到'\0'结束
	cout << s1 << endl;
	getline(cin, s2, '!'); //指定结束符号
	cout << s2 << endl;
}
int main()
{
    
    
	test_getline();
	return 0;
}

在这里插入图片描述

operator>>operator<<

流插入和流提取运算符重载

在这里插入图片描述

在这里插入图片描述

2.6vs和g++下string结构的说明

注意:下述结构是在32位平台下进行验证,32位平台下指针占4个字节

vs下string的结构

VS下string的结构

string总共占28个字节,内部结构稍微复杂一点,先是有一个联合体,联合体用来定义string中字符串的存储间:

1.当字符串长度小于16时,使用内部固定的字符数组来存放

2.当字符串长度大于等于16时,从堆上开辟空间

union _Bxty
{
    
    
    // storage for small buffer or pointer to larger one
    value_type _Buf[_BUF_SIZE];
    pointer _Ptr;
    char _Alias[_BUF_SIZE]; // to permit aliasing
} _Bx;

这种设计也是有一定道理的,大多数情况下字符串的长度都小于16,那string对象创建好之后,内部已经有了16个字符数组的固定空间,不需要通过堆创建,效率高,其次:还有一个size_t字段保存字符串长度,一个size_t字段保存从堆上开辟空间总的容量,最后.还有一个指针做一些其他事情

故总共占16+4+4+4=28个字节

在这里插入图片描述

总的来说,VS下string结构是一种以空间换时间的做法

g++下string的结构

g++下,string是通过写时拷贝实现的,string对象总共占4个字节,内部只包含了一个指针,该指针将来指向一块堆空间,内部包含了如下字段:

1.空间总大小(capacity)

2.字符串有效长度(size)

3.引用计数(refcount)拷贝构造时默认使用浅拷贝来提高效率+使用引用计数来保证同一块堆空间不被析构多次

引用计数 是计算机编程语言中的一种内存管理技术,是指将资源(可以是对象 ,内存或磁盘空间等)的被引用次数保存起来,当被引用次数变为零时就将其释放的过程

4.指向堆空间的指针,用来存储字符串

三、string类的模拟实现

string.h

#pragma once

// 用命名空间域保存起来,避免与库里的string冲突
namespace hdp
{
    
    
	class string
	{
    
    
	public:
		typedef char* iterator; //迭代器
		typedef const char* const_iterator;  //const迭代器
		iterator begin()
		{
    
    
			return _str;
		}

		iterator end()
		{
    
    
			return _str + _size;
		}

		// 构造函数
		string(const char* str = "")
		{
    
    
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity + 1];

			strcpy(_str, str);
		}

		// 析构函数
		~string()
		{
    
    
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}

		//转换为C语言的字符串
		const char* c_str()  const
		{
    
    
			return _str;
		}

		// 获取size
		size_t size()  const
		{
    
    
			return _size;
		}

		//获取capacity
		size_t capacity()  const
		{
    
    
			return _capacity;
		}

		// 字符串交换
		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 = new char[s._capacity + 1];
		//	_size = s._size;
		//	_capacity = s._capacity;

		//	//将s的数据拷贝到str中
		//	strcpy(_str, s._str);
		//}

		//拷贝构造 --现代写法  s2(s1)
		string(const string& s)
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
		{
    
    
			string tmp(s._str); // 构造函数
			//this->swap(tmp);
			swap(tmp);
		}

		 赋值重载 s1 = s2 --传统写法
		//string& operator=(string s)
		//{
    
    
		//	// 检查自我赋值
		//	if (this != &s)
		//	{
    
    
		//		char* tmp = new char[s._capacity + 1];
		//		strcpy(_str, tmp);

		//		delete[] _str;
		//		_str = tmp;

		//		_size = s._size;
		//		_capacity = s._capacity;

		//	}
		//	return *this;
		//}

		 s1 = s3 --赋值重载  现代写法1
		//string& operator=(const string& s)
		//{
    
    
		//	// 检查自我赋值
		//	if (this != &s)
		//	{
    
    
		//		// string tmp(s._str);
		//		string tmp(s);
		//		swap(tmp);
		//	}
		//	return *this;
		//}

		// // s1 = s3 --赋值重载  现代写法2
		string& operator=(string s)
		{
    
    
			swap(s);
			return *this;
		}

		//重载opertaor[]
		// 普通对象:可读可写
		char& operator[](size_t pos)
		{
    
    
			assert(pos < _size);
			return _str[pos];
		}

		// const对象:只读
		const char& operator[](size_t pos) const
		{
    
    
			assert(pos < _size);
			return _str[pos];
		}

		// 预留空间
		void reserve(size_t n)
		{
    
    
			// n大于_capacity才进行扩容
			if (n > _capacity)
			{
    
    
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = n;
			}
		}

		//调整空间大小
		void resize(size_t n, char ch = '\0')
		{
    
    
			// n大于_capacity
			if (n > _capacity)
			{
    
    
				reserve(n);
				for (size_t i = _size; i < n; i++)
				{
    
    
					_str[i] = ch;
				}
				_size = n;
				_str[_size] = '\0';
			}
			// n>_size&&n<_capacity   n<_size
			else
			{
    
    
				_size = n;
				_str[_size] = '\0';
			}
		}

		// 尾插一个字符
		void push_back(char ch)
		{
    
    
			// 空间不够进行扩容
			if (_size == _capacity)
			{
    
    
				size_t newCapacity = _capacity == 0 ? 4 : _capacity * 2;
				reserve(newCapacity);
			}
			_str[_size] = ch;

			// ++size并将_size位置数据置为'\0'
			++_size;
			_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
			push_back(ch);
			return *this;
		}

		//+=一个字符串
		string& operator+=(const char* str)
		{
    
    
			// 直接调用append
			append(str);
			return *this;
		}

		//在pos位置插入一个字符
		string& insert(size_t pos, char ch)
		{
    
    
			// 断言pos的位置
			assert(pos <= _size);
			// 空间不够进行扩容
			if (_size == _capacity)
			{
    
    
				int newCapacity = _capacity == 0 ? 4 : _capacity * 2;
				reserve(newCapacity);
			}

			 挪动数据
			//int end = _size;
			//while (end >= (int)pos)
			//{
    
    
			//	_str[end + 1] = _str[end];
			//	--end;
			//}

			size_t end = _size + 1;
			while (end > pos)
			{
    
    
				_str[end] = _str[end - 1];
				--end;
			}

			_str[pos] = ch;
			++_size;

			return *this;
		}

		//在pos位置插入一个字符串
		string& insert(size_t pos, const char* str)
		{
    
    
			// 断言pos的位置
			assert(pos <= _size);

			size_t len = strlen(str);
			// 空间不够进行扩容
			if (_size + len > _capacity)
			{
    
    
				reserve(_size + len);
			}

			// 挪动数据
			/*int end = _size;
			while (end >= (int)pos + len)
			{
				_str[end +len] = _str[end];
				--end;
			}*/

			size_t end = _size + 1;
			while (end > pos + len - 1)
			{
    
    
				_str[end] = _str[end - len];
				--end;
			}

			strncpy(_str + pos, str, len);
			_size += len;

			return *this;
		}

		//删除pos之后n个数据
		string& erase(size_t pos, size_t len = npos)
		{
    
    
			// 断言pos的位置
			assert(pos < _size);

			//删除的个数等于npos或者删除的个数大于pos位置之后的数据,则直接在pos位置设置为'\0'即可
			if (len == npos || pos + len >= _size)
			{
    
    
				_str[pos] = '\0';
				_size -= len;
			}
			else
			{
    
    
				strcpy(_str + pos, _str + pos + len);
				_size -= len;
			}

			return *this;
		}

		//查找为ch的字符,默认从0开始找
		size_t find(char ch, size_t pos = 0) const
		{
    
    
			// 断言pos的位置
			assert(pos < _size);

			//遍历查找
			while (pos < _size)
			{
    
    
				if (_str[pos] == ch)
				{
    
    
					return pos;
					++pos;
				}
			}
			// 查找不到返回npos
			return npos;
		}

		//从pos位置开始查找一个字符串
		size_t find(const char* str, size_t pos = 0) const
		{
    
    
			// 断言pos的位置
			assert(pos < _size);

			const char* ptr = strstr(_str + pos, str);
			if (ptr == nullptr)
			{
    
    
				return npos;
			}
			return ptr - _str;
		}
		// 清理空间
		void clear()
		{
    
    
			_size = 0;
			// 将下标为0位置的数据设置为'\0'
			_str[_size] = '\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)
	{
    
    
		//提取之前先清理数据 避免string s1有数据还输入数据
		s.clear();

		//char ch = in.get();
		输入不为空格和换行就继续输入
		//while (ch != ' ' && ch != '\n')
		//{
    
    
		//	s += ch;
		//	//in >> ch;
		//	ch = in.get();
		//}

		char buff[128] = {
    
     '\0' };
		size_t i = 0;
		char ch = in.get();
		while (ch != ' ' && ch != '\n')
		{
    
    
			if (i == 127)
			{
    
    
				// 满了
				s += buff;
				i = 0;
			}
			buff[i++] = ch;

			ch = in.get();
		}

		// buff里面的数据添加到s中
		if (i > 0)
		{
    
    
			buff[i] = '\0';
			s += buff;
		}

		return in;
	}

}

test.cpp

#include <iostream>
#include <assert.h>
#include "string.h"
using namespace std;

// 测试三种遍历方式
void test_string1()
{
    
    
	hdp::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;

	hdp::string::iterator it1 = s1.begin();
	while (it1 != s1.end())
	{
    
    
		(*it1)--;

		++it1;
	}
	cout << s1.c_str() << endl;


	for (auto ch : s1)
	{
    
    
		cout << ch << " ";
	}
	cout << endl;

}

// 测试+=
void test_string2()
{
    
    
	hdp::string s1("hello");
	s1 += ' ';
	s1 += '!';
	cout << s1.c_str() << endl;

	s1 += "world hello world";
	cout << s1.c_str() << endl;
}

// 测试插入
void test_string3()
{
    
    
	hdp::string s1("helloworld");
	cout << s1.c_str() << endl;

	s1.insert(5, ' ');
	cout << s1.c_str() << endl;

	s1.insert(0, 'x');
	cout << s1.c_str() << endl;

	hdp::string s2("helloworld");
	cout << s2.c_str() << endl;
	s2.insert(5, " + ");
	cout << s2.c_str() << endl;

	s2.insert(0, "hello ");
	cout << s2.c_str() << endl;

	s2.insert(0, "x");
	cout << s2.c_str() << endl;

	hdp::string s3;
	s3.insert(0, "");
	cout << s3.c_str() << endl;
}


//测试删除
void test_string4()
{
    
    
	hdp::string s1("hello hello world");
	s1.erase(0, 6);
	cout << s1.c_str() << endl;

	s1.erase(5);
	cout << s1.c_str() << endl;
}

//测试resize
void test_string5()
{
    
    
	hdp::string s1("hello world");
	s1.resize(5);
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
	cout << s1.c_str() << endl << endl;

	hdp::string s2("hello world");
	//s2.resize(15);
	s2.resize(15, 'x');
	cout << s2.size() << endl;
	cout << s2.capacity() << endl;
	cout << s2.c_str() << endl << endl;

	hdp::string s3("hello world");
	s3.resize(20, 'x');
	cout << s3.size() << endl;
	cout << s3.capacity() << endl;
	cout << s3.c_str() << endl << endl;
}

// 测试流插入和流提取
void test_string6()
{
    
    
	hdp::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;


	cin >> s1;
	cout << s1 << endl;


	hdp::string s2;
	cin >> s2;
	cout << s2 << endl;

	hdp::string s3;
	cin >> s3;
	cout << s3 << endl;
}

//测试拷贝构造和赋值重载
void test_string7()
{
    
    
	hdp::string s1("hello world");
	hdp::string s2(s1);

	cout << s1 << endl;
	cout << s2 << endl;

	hdp::string s3("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
	s1 = s3;
	cout << s1 << endl;
	cout << s3 << endl;

	s1.swap(s2);
	swap(s1, s2);
	cout << s1 << endl;
	cout << s2 << endl;

}

int main()
{
    
    
	//test_string1();
	//test_string2();
	//test_string3();
	//test_string4();
	//test_string6();
	//test_string7();
	return 0;
}

四、深浅拷贝

1.浅拷贝

浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来。如果对象中管理资源,最后就会导致多个对象共享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为还有效,所以当继续对资源进项操作时,就会发生发生了访问违规。

就像一个家庭中有两个孩子,但父母只买了一份玩具,两个孩子愿意一块玩,则万事大吉,万一不想分享就你争我夺,玩具损坏

在这里插入图片描述

可以采用深拷贝解决浅拷贝问题,即:每个对象都有一份独立的资源,不要和其他对象共享

在这里插入图片描述

2.深拷贝

如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。

在这里插入图片描述

3.写时拷贝(了解)

在这里插入图片描述

写时拷贝就是一种拖延症,是在浅拷贝的基础之上增加了引用计数的方式来实现的。

引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成1,每增加一个对象使用该资源,就给计数增加1,当某个对象被销毁时,先给该计数减1,然后再检查是否需要释放资源,如果计数为1,说明该对象时资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有其他对象在使用该资源

下面有两篇关于写时拷贝的文章,有兴趣的小伙伴可以看看:

写时拷贝

写时拷贝在读取时的缺陷

猜你喜欢

转载自blog.csdn.net/qq_67582098/article/details/129673853