前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >STL-string类

STL-string类

作者头像
发布2024-12-15 09:06:20
发布2024-12-15 09:06:20
5500
代码可运行
举报
文章被收录于专栏:转自CSDN转自CSDN
运行总次数:0
代码可运行

string类的意义

C语言原始的字符串

字符串是以'\0'结尾的字符的合集,为了方便操作,C标准库提供了一些str系列的库函数,但是这些库函数与字符串分离开,并不符合OOP的思想,底层又需要用户自己去管理,稍不注意就会越界访问

字符串类题目

在OJ题目中,并不再使用C语言库中的字符串操作函数,而是用封装好的string类函数

415. 字符串相加 - 力扣(LeetCode)415. 字符串相加 - 力扣(LeetCode)

代码语言:javascript
代码运行次数:0
复制
class Solution
{
public:
    string addStrings(string num1, string num2) {
        string* max = &num1; string* min = &num2;
        if ((*min).size() > (*max).size())
        {
            max = &num2;
            min = &num1;
        }
        for (std::string::reverse_iterator rita = min->rbegin(), ritb = max->rbegin(); rita != min->rend(); ++rita, ++ritb)
        {
            *ritb += *rita - '0';
        }
        int b = 0;
        for (std::string::reverse_iterator rita = max->rbegin(); rita + 1 != max->rend(); ++rita)
        {
            b = *rita - '0';
            if ((*rita) > '9' && rita + 1 != max->rend());
            {
                *rita -= 10;
                *(rita + 1) += 1;
            }
        }
        if (max->front() > '9')
        {
            max->front() -= 10;
            max->insert(0, 1, '1');
        }


        return (*max);
    }
};

string类

string类文档

cplusplus.com/reference/string/string/?kw=string

auto和范围for

auto是个关键字

早期C/C++的auto是,使用auto修饰的变量,是具有自动存储器的局部变量,后来这这个不再重要了 在C++11中规定,auto不再是一个存储类型指示符,而是一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而来的 当auto声明指针类型时,用auto和auto*并没有区别 当auto声明引用时,必须用auto& 当auto声明一整行多个变量时,这些变量必须是同一个类型 auto不能作为函数的参数,但是可以当返回值 auto不能用来声明数组

代码语言:javascript
代码运行次数:0
复制
auto a()
{
	return 10;
}

auto& b()
{
	static int num = 10;
	return num;
}

//void c(auto a)是错误的

int main()
{
	int c = 10;
	auto e = c;
	auto& f = e;

	cout << a() << endl;

	auto& g = b();
	b()++;
	cout << g << endl;
}

范围for

对于有范围的集合,c++11引入了基于范围的for循环 for循环后的括号由冒号":"分为两部分 第一部分是变量,第二部分为被迭代的范围 它会自动取数据,自动迭代,自动判断结束 for可以用在数组和容器对象上进行遍历 for的底层是迭代器

代码语言:javascript
代码运行次数:0
复制
int main()
{
	char string[] = "abcdefg";
	for (auto it : string)
	{
		cout << it << ' ';
	}
	for (auto& it : string)
	{
		cout << it << ' ';
	}
	for (const auto it : string)
	{
		cout << it << ' ';
	}
}

string类的接口

构造

构造函数名称

功能说明

string()

构造空的string类对象

string(const char* s)

用C-string构造stirng类对象

string(size_t n,char c)

string类对象中包含n个字符c

string(const string&s)

拷贝构造函数

代码语言:javascript
代码运行次数:0
复制
int main()
{
	string a;//空构造
	string b("hello");//用C字符串构造
	string c(b);//拷贝构造
	string d(5, 'a');//n个字符串c
	string e(b.begin(), b.end());//指针构造

}

容量

size

返回字符串有效长度

length

返回字符串有效长度

capacity

返回空间总大小

empty

检测字符串是否为空

clear

清空字符串

reserve

为字符串预留空间

resize

将字符串的个数改成n个多处的空间用c填充

代码语言:javascript
代码运行次数:0
复制
int main()
{
	string A = { 'a','a','c'};
	cout << A.size() << ' ' << A.length();
	cout << endl;
	cout << A.capacity() << endl;
	A.clear();
	cout << A.size() << ' ' << A.capacity();
	cout << endl;
	A.reserve(A.capacity() + 5);
	cout << A.size() << ' ' << A.capacity();
	cout << endl;
	A.resize(5, 'x');
	cout << A.size() << ' ' << A.capacity() << ' ' << A.empty();
	cout << endl;
	A.reserve(A.capacity() - 5);//无法减小的
	cout << A.size() << ' ' << A.capacity();
	cout << endl;
	A.resize(0);//可以减小size
	cout << A.size() << ' ' << A.capacity() << ' ' <<A.empty();
	cout << endl;
}

size()与length()底层完全相同 clear()只是清理有效字符,不改变底层申请空间大小 resize可以增多字符串大小也可以减小字符串大小 reserve只会增加capacity不会减小预留空间

遍历操作

operator[]

返回pos位置的字符

begin+end

begin获取一个字符串的迭代器+end获取最后一个字符下一个位置的迭代器

rbegin+rend

rbegin最后一个字符串的迭代器,rend获得第一个字符串上一个的位置的迭代器

for

C++11提供的更简洁的遍历方式

代码语言:javascript
代码运行次数:0
复制
int main()
{
	string A = { 'a','b','c'};
	cout << A[1] << endl;
	for (auto it : A)
		cout << it << ' ';
	cout << endl;
	return 0;
}

类对象修改操作

push back

在字符串末尾插入c

append

追加字符串

operator+=

追加字符串

c_str

返回c格式字符串

find+npos

从字符串pos位置开始寻找字符c,返回该字符在字符串的位置

rfind

从pos位置往前找

substr

在str中从pos位置开始,截取n个字符,然后将其返回

代码语言:javascript
代码运行次数:0
复制
int main()
{
	string A = { 'a','b','c'};
	A.push_back('d');
	A.append(" abcd");
	A += " bcda";
	cout<<A.c_str()<<endl;
	cout<<A.find('b')<<endl;
	cout << A.rfind('d') << endl;
	cout << A.substr(A.find('b'), A.rfind('d') - A.find('b')) << endl;
}

非成员函数

operator+

传值返回

operator>>

运算符重载

operator<<

输出运算符重载

getline

获取一行字符串

relational operators

大小比较

代码语言:javascript
代码运行次数:0
复制
int main()
{
	string A;
	
	cin >> A;
	for (auto it : A)
		cout << it;

	getline(cin, A);

	for (auto it : A)
		cout << it;
}

string的模拟实现

首先是头文件

代码语言:javascript
代码运行次数:0
复制
#pragma once
#include<iostream>
using std::ostream;
using std::istream;

namespace bit
{

    class string
    {

        friend ostream& operator<<(ostream& _cout, const bit::string& s);

        friend istream& operator>>(istream& _cin, bit::string& s);

    public:

        typedef char* iterator;

    public:

        string(const char* str = "");//

        string(const string& s);//

        string& operator=(const string& s)//
        {
            string tmp(s);
            this->swap(tmp);
        }

        ~string();//



            //

            // iterator

        iterator begin()
        {
            return _str;
        }

        iterator end()
        {
            return _str + _size;
        }



            /

            // modify

        void push_back(char c)
        {
            if (_size == _capacity)
            {
                reserve(_capacity * 2);
            }
            _str[_size++] = c;
            _str[_size] = '\0';
        }

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

        void append(const char* str)
        {
            *this += str;
        }

        string& operator+=(const char* str)
        {
            for (int i = 0; str[i] != '\0'; i++)
            {
                push_back(str[i]);
            }
            return *this;
        }

        void clear()
        {
            _size = 0;
        }

        void swap(string& s);//

        const char* c_str()const
        {
            return _str;
        }



        /

        // capacity

        size_t size()const
        {
            return _size;
        }

        size_t capacity()const
        {
            return _capacity;
        }

        bool empty()const
        {
            return _size == 0 ? true : false;
        }

        void resize(size_t n, char c = '\0')
        {
            if (n > _size)
            {
                if (n > _capacity)
                {
                    reserve(n);
                }

                memset(_str + _size, c, n - _size);
            }
        }

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

                delete[] _str;
                _str = str;
                _capacity = n;
            }
        }



        /

        // access

        char& operator[](size_t index)
        {
            return _str[index];
        }

        const char& operator[](size_t index)const
        {
            return _str[index];
        }



        /

        //relational operators

        bool operator<(const string& s)
        {
            if (this->_size < s._size)
            {
                return true;
            }
            return false;
        }

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

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

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

        bool operator==(const string& s)
        {
            if (_size == s._size)
            return true;
        }

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



        // 返回c在string中第一次出现的位置

        size_t find(char c, size_t pos = 0) const
        {
            for (int i = 0; i < _size; i++)
            {
                if (_str[i] == c)
                    return i;
            }
            return  - 1;
        }

        // 返回子串s在string中第一次出现的位置

        size_t find(const char* s, size_t pos = 0) const
        {
            const char* tmp = strstr(_str, s);
            if (tmp == nullptr)
            {
                return -1;
            }
            return tmp - _str;
        }

        // 在pos位置上插入字符c/字符串str,并返回该字符的位置

        string& insert(size_t pos, char c)
        {
            if (_size == _capacity)
            {
                reserve(_capacity * 2);
            }
            *this += '\0';
            for (int i = _size; i > pos; i--)
            {
                _str[i] = _str[i - 1];
            }
            _str[pos] = c;
            return *this;
        }

        string& insert(size_t pos, const char* str)
        {
            for (int i = 0; i < strlen(str); i++)
            {
                this->insert(pos, str[strlen(str) - i - 1]);
            }
            return *this;
        }



        // 删除pos位置上的元素,并返回该元素的下一个位置

        size_t erase(size_t pos, size_t len)
        {
            if (len >= _size - pos)
            {
                _size = 0;
            }
            else
            {
                for (int i = pos;i + len < _size;i++)
                {
                    _str[i] = _str[i + len];
                }
                _size -= len;
            }
            return _size - pos;
        }

    private:

        char* _str;

        size_t _capacity;

        size_t _size;

    };
};

然后是实现文件

代码语言:javascript
代码运行次数:0
复制
#define _CRT_SECURE_NO_WARNINGS
#include "my_string.h"

using namespace bit;
string::string(const char* str)
{
	_size = strlen(str);
	_capacity = _size;
	_str = new char[_capacity + 1];
	strcpy(_str, str);
}

string::string(const string& s)
{
	_str = nullptr;
	_size = 0;
	_capacity = 0;
	string tmp(s._str);
	this->swap(tmp);
}

void string::swap(string& s)
{
	std::swap(_str, s._str);
	std::swap(_size, s._size);
	std::swap(_capacity, s._capacity);
}

string::~string()
{
	if (_str)
	{
		delete[] _str;
		_str = nullptr;
	}
}

ostream& bit::operator<<(ostream& _cout, const bit::string& s)
{
	for (size_t i = 0; i < s.size(); ++i)
	{
		_cout << s[i];
	}
	return _cout;
}

istream& bit::operator>>(istream& _cin, bit::string& s)
{
	s._size = s._capacity = 0;
	char c;
	
	while (1)
	{
		c = std::getchar();
		if (c == ' '|| c=='\n')
		{
			return _cin;
		}
		s += c;
	}
	return _cin;
}

浅拷贝

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

可以理解浅拷贝是对类直接管理的成员变量进行一个字节一个字节的拷贝

深拷贝

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

可以认为深拷贝,是用户自己写的更好的拷贝方式

写时拷贝

写时拷贝是在浅拷贝的基础上增加了引用计数的方式实现

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-12-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • string类的意义
    • C语言原始的字符串
    • 字符串类题目
  • string类
    • string类文档
    • auto和范围for
      • auto是个关键字
    • 范围for
    • string类的接口
  • string的模拟实现
  • 浅拷贝
  • 深拷贝
  • 写时拷贝
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档