STL篇:string的用法及模拟实现

STL六大组件:

ce0d982fa7b146109fd1e05ec70bcf1c.png

一、string的介绍以及用法

1、C strxxx系列库函数。c的字符数组,以\0为终止算长度
  cpp string管理字符数组:增删查改+算法(属于std类)。string不看\0,以size为终止算长度
2、迭代器
 · iterator是像指针一样的类型,有可能是指针有可能不是指针
 · 范围for(底层替换为迭代器)
 · 迭代器可以跟容器进行配合,任何容器都支持迭代器,并且用法是类似
总结:Iterate提供一种统一的方式访问和修改容器的数据,算法就可以通过迭代器去处理容器中的数据
 · 除此之外,还有反向迭代器(没有倒着遍历的范围for),const迭代器
3、内存管理
reserve:开空间(不需要+1,只需要写有效字符数量即可)
resize:开空间+填值初始化(默认)
clear:只清数据,底层判断是否缩容(看编译器)(一般不缩)
shrink_to_fit:缩容至适合
4、增删查改
 · []与at(像数组一样访问)
 · cin读取不能有空格和换行,故可用getline(非string成员函数)取一行
 · push_back(尾插字符),append(尾插字符串)与assign(覆盖)
 · insert(插入)与erase(清除)
 · 赋值运算符的重载只能有一个参数
5、c的一些接口配合.c_str()

二、string的模拟实现以及测试

模拟实现

//string.h
#pragma once

#include<assert.h>

#include<iostream>
using namespace std;

namespace star
{
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;
		//迭代器:任何容器都支持迭代器,并且用法类似
		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		const_iterator begin() const
		{
			return _str;
		}

		const_iterator end() const
		{
			return _str + _size;
		}
		//构造函数
		//内置类型初始化列表初始化和函数初始化均可,自定义类型尽量在初始化列表初始化
		//错误写法:
		//string(const char* str = '/0')//字符和字符串类型不匹配
		//string(const char* str = nullptr)//strlen报错
		//string()
		//		:_size(0)
		//		,_capacity(0)
		//		,_str(nullptr)
		//		{}//会导致c_str传nullptr
		//正确写法:
		/*string(const char* str = "")
			:_size(strlen(str))
			, _capacity(_size)
			, _str(new char[_capacity+1])
		{
			strcpy(_str, str);
		}*/

		/*string()
			:_size(0)
			, _capacity(0)
			, _str(new char[1])
		{
			strcpy(_str, "\0");
			//_str[0] = '\0';
		}*/
		string(const char* str = "")//若填"\0",则缺省参数有两个"\0"
		{
			_size = strlen(str);//所以memcpy要+1(\0)
			_capacity = _size;
			_str = new char[_capacity + 1];
			memcpy(_str, str, _size + 1);
		}
		//拷贝构造(深拷贝)
		string(const string& s)
		{
			_str = new char[s._capacity + 1];
			memcpy(_str, s._str, s._size + 1);
			_size = s._size;
			_capacity = s._capacity;
		}
		//析构函数
		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}
		//c的一些接口配合
		const char* c_str() const
		{
			return _str;
		}

		size_t size() const
		{
			return _size;
		}

		char& operator[](size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}
		//开空间
		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				/*	错误写法
					char* tmp = new char[_capacity + n];
					memcpy(tmp, _str);
					delete[] _str;
					_str = tmp;
					_size = _capacity += n;*/
			}
			//正确写法
			char* tmp = new char[n + 1];//多开一个给'\0'('\0'不算有效字符)
			memcpy(tmp, _str, _size + 1);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}
		//开空间+填值初始化
		void resize(size_t n, char ch = '\0')
		{
			if (n < _size)
			{
				_size = n;
				_str[_size] = '\0';
			}
			else
			{
				reserve(n);
				for (size_t i = _size; i < n; i++)
				{
					_str[i] = ch;
				}
				_size = n;
				_str[_size] = '\0';
			}
		}
		//尾插一个字符
		void push_back(char ch)
		{
			if (_size == _capacity)
			{
				reserve(_capacity = 0 ? 4 : _capacity * 2);
			}
			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';
		}
		//尾插一个字符串
		void append(const char* str)
		{
			size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}
			memcpy(_str + _size, str, len + 1);
			/*_capacity =(reserve里已经修改了capacity了) */_size += len;
		}
		//尾插一个字符
		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}

		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}
		//插入
		void insert(size_t pos, size_t n, char ch)
		{
			assert(pos < _size);
			if (_size + n > _capacity)
			{
				reserve(_size + n);
			}
			size_t end = _size;
			while (end >= pos && end != npos)
			{
				_str[end + n] = _str[end];
				--end;
			}
			for (size_t i = 0; i < n; i++)
			{
				_str[pos + i] = ch;
			}
			_size += n;
		}

		void insert(size_t pos, const char* str)
		{
			assert(pos < _size);
			size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}
			size_t end = _size;
			while (end >= pos && end != npos)
			{
				_str[end + len] = _str[end];
				--end;
			}
			for (size_t i = 0; i < pos; i++)
			{
				_str[pos + i] = str[i];
			}
			_size += len;
		}
		//清除
		void erase(size_t pos, size_t len = npos)
		{
			assert(pos <= _size);
			if (len == npos || len + pos >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				size_t end = pos + len;
				while (end <= _size)
				{
					_str[pos++] = _str[end++];
				}
				_size -= len;
			}

		}

		size_t find(char ch, size_t pos = 0)
		{
			assert(pos < _size);
			for (size_t i = pos; i < _size; i++)
			{
				if (ch == _str[i])
				{
					return i;
				}
			}
			return npos;
		}

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

		string substr(size_t pos = 0, size_t len = npos)
		{
			assert(pos < _size);
			size_t n = len;
			if (len == npos || pos + len > _size)
			{
				n = _size - pos;
			}
			string tmp;
			tmp.reserve(n);

			for (size_t i = pos; i < pos + n; i++)
			{
				tmp += _str[i];
			}

			return tmp;
		}

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

		void swap(string& s)
		{
			std::swap(_capacity, s._capacity);
			std::swap(_size, s._size);
			std::swap(_str, s._str);
		}
		//赋值重载(现代写法)
		string operator=(string tmp)
		{
			swap(tmp);
			return *this;
		}

		bool operator<(const string& s)
		{
			int ret = memcmp(_str, s._str, _size < s._size ? _size : s._size);
			return ret == 0 ? _size < s._size : ret < 0;
		}

		bool operator==(const string& s)
		{
			return _size == s._size && memcmp(_str, s._str, _size);
		}

		bool operator>(const string& s)
		{
			return !(*this <= s);
		}

		bool operator<=(const string& s)
		{
			return *this < s || *this == s;
		}

		bool operator>=(const string& s)
		{
			return *this > s || *this == s;
		}

	private:
		size_t _capacity;
		size_t _size;
		char* _str;

	public:
		//const static size_t npos = -1;
		const static size_t npos;//类内声明
	};

	const size_t string::npos = -1;//类外定义
}

测试

//test.cpp
#define  _CRT_SECURE_NO_WARNINGS 1

#include"string.h"

void test_string1()
{
	star::string s1("hello world");
	cout << s1.c_str() << endl;

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

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

	const star::string s2("hello world");
	/*s2[0] = 'H';*/

//可读可写
	star::string::iterator it = s1.begin();
	while (it != s1.end())
	{
		*it += 1;

		cout << *it << " ";
		++it;
	}
	cout << endl;

	//可读不可写
		/*star::string::const_iterator cit = s2.begin();*/
	auto cit = s2.begin();
	while (cit != s2.end())
	{
		//*cit += 1;

		cout << *cit << " ";
		++cit;
	}
	cout << endl;

	//auto根据表达式自动推导类型:需迭代器支持
	//typeid(x).name()打印类型
	//语法糖:(适用于数组)范围for(依次取数组中的数据赋值给e,自动迭代,自动判断结束)
	for (auto ch : s1)
	{
		cout << ch << " ";
	}
	cout << endl;

	star::string s3(s1);
	cout << s3.c_str() << endl;

	star::string s4;
	s4 = s1;
	cout << s4.c_str() << endl;
}

void test_string2()
{

	star::string s1("hello world");
	cout << s1.c_str() << endl;

	s1.push_back(' ');
	s1.push_back('#');
	s1.append("hello star");
	cout << s1.c_str() << endl;

	star::string s2("hello world");
	cout << s2.c_str() << endl;

	s2 += ' ';
	s2 += '#';
	s2 += "hello star";
	cout << s2.c_str() << endl;
}

void test_string3()
{
	star::string s1("helloworld");
	cout << s1.c_str() << endl;

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

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

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

void test_string4()
{
	star::string url = "https://www.bytedance.com/zh/";//网址的输入格式:协议+域名+路径

	size_t pos1 = url.find("://");
	if (pos1 != star::string::npos)
	{
		star::string protocol = url.substr(0, pos1);
		cout << protocol.c_str() << endl;
	}

	size_t pos2 = url.find('/', pos1 + 3);
	if (pos2 != star::string::npos)
	{
		star::string domain = url.substr(pos1 + 3, pos2 - (pos1 + 3));
		star::string uri = url.substr(pos2 + 1);

		cout << domain.c_str() << endl;
		cout << uri.c_str() << endl;
	}
}

void test_string5()
{
	star::string s1("hello star");
	star::string s2("hello galaxy");
	cout << (s1 < s2) << endl;
	cout << (s1 > s2) << endl;
	cout << (s1 == s2) << endl << endl;
}

三、再谈深浅拷贝

 · 以上代码中,拷贝构造若使用现代写法(swap),则必须使用初始化列表初始化。因为不能保证每个编译器都将其初始化(C++规定内置类型不做处理)。若未能对成员变量初始化,拷贝构造中的swap将交换实参的引用以及tmp成员变量随机值,tmp出作用域析构时将报错。

string(string& s)
	: _size(0)
	, _capacity(0)
	, _str(nullptr)
{
	string tmp = s._str;
	swap(tmp);
}

 · 写时拷贝/延迟拷贝
浅拷贝问题:
1、析构两次(引用计数解决):最后一个管理此块空间的对象对其析构(最后一个走的人关灯)
2、一个对象修改影响另一个(延迟拷贝解决):写的时候引用计数如果不是1,则进行深拷贝,再修改

四、Buf数组

在VS2019中,若字符串size<16,则存在buff数组中(以空间换时间),若字符串size>=16,则存在_ptr指向的堆空间中。

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值