c++虫洞 STL string

简介: c++虫洞 STL string


文章目录



STL

什么是STL

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

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)采用,可移植性好,可公开、修改甚至贩卖,从命名风格和编程 风格上看,阅读性非常高。我们后面学习STL要阅读部分源代码,主要参考的就是这个版本。

STL的六大组件

如何学习STL

简单总结一下:

学习STL的三个境界:

  1. 能用,
  2. 明理,
  3. 能扩展 。

进公司前要把前两层修炼熟悉,第三层是在公司中修炼的

STL的缺陷

  1. STL库的更新太慢了。这个得严重吐槽,上一版靠谱是C++98,中间的C++03基本一些修订。C++11出
    来已经相隔了13年,STL才进一步更新。
  2. STL现在都没有支持线程安全。并发环境下需要我们自己加锁。且锁的粒度是比较大的。
  3. STL极度的追求效率,导致内部比较复杂。比如类型萃取,迭代器萃取。
  4. STL的使用会有代码膨胀的问题,比如使用vector/vector/vector这样会生成多份代码,当然这是模板语
    法本身导致的。

接下来我们要学的第一个容器就是string

为什么学习string类?

C语言中的字符串

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

标准库中的string类

string类(了解)

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;

string类的常用接口说明(注意下面我只讲解最常用的接口)

1.string类对象的常见构造

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

学STL,重点讲最常用30%左右的接口函数,其他很少用,如果有一天我们需要用,就去看文档

int main()
{
  string s1;              //无参构造
  string s2("Hello c++"); //带参数构造
  string s3 = "Hello c++";//编译器优化的直接构造
  string s4(s2);          //拷贝构造
  string s5(s4, 2, string::npos);    //部分构造
  string s6("123456789", 5);         //构造前n个字符
  //这个作用就是假如以后要写网络的代码,截取前几个字符会用到
  const char* url = "http://www.cplusplus.com/reference/string/string/string/";
  string s7(url, 5);
  string s8(10, 'x');     //构造n个一样的字符
  cout << s1 << endl;
  cout << s2 << endl;
  cout << s3 << endl;
  cout << s4 << endl;
  cout << s5 << endl;
  cout << s6 << endl;
  cout << s7 << endl;
  cout << s8 << endl;
  return 0;
}

2.string类对象的容量操作

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

实际上length在string中就是数组长度,和size一样,那为什么要两个一样的呢,是因为历史上string出来的要比stl早,string在官网文档也没有归类到容器里面(但他就是容器),而是放在了头文件里面,size是普法,length是只用与string的

注意:

  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不会改变容量大小。

这里提一嘴 at 的作用和 [] 是一样的,可以认为是早期语法可能不太支持 [] 所以才有at这个接口代替,后面支持了,at就基本不用了,他们也不是完全一样,他们越界就不一样

reserve给足空间就可以防止多次增容,那么resize可以吗

我们也可以看看相同的代码在不同平台跑出来的结果

int main()
{
  string s1 = "Hello world";
  string s2 ="world";
  //判断字符串是否为空
  cout <<"s1.empty "<< s1.empty() << endl;
  cout << "s2.empty " << s2.empty() << endl;
  //大小
  cout << "s1.size " << s1.size() << endl;
  cout << "s2.size " << s2.size() << endl;
  //容量
  cout <<"s1.capacity "<< s1.capacity() << endl;
  cout <<"s2.capacity "<< s2.capacity() << endl << endl;
  //清掉所有的数据,就是size变成零,但是空间不释放
  s1.clear();
  cout << "s1.size " << s1.size() << endl;
  cout << "s1.capacity " << s1.capacity() << endl << endl;
  //在对象中插入n个字符,默认字符是‘\0’
  //想要放其他字符就
  s1.resize(15);
  string s3 = s2;
  s2.resize(1,'x');
  s3.resize(16,'x');
  cout <<"s2:    "<< s2 << endl;
  cout <<"s3:    "<< s3 << endl;
  cout << "s1.size " << s1.size() << endl;
  cout << "s2.size " << s2.size() << endl;
  cout << "s1.capacity " << s1.capacity() << endl;
  cout << "s2.capacity " << s2.capacity() << endl << endl;
  //请求一个容量的改变  
  s2.reserve(40);
  cout << "s2:    " << s2 << endl;
  cout << "s2.size " << s2.size() << endl;
  cout << "s2.capacity " << s2.capacity() << endl << endl;
  string s4;
  直接给足空间防止多次增容  
  //s4.reserve(127);
  //看看resize可不可以防止多次增容
  s4.resize(127);
  int old_capacity = s4.capacity();
  for (char ch = 0; ch < 127; ch++)
  {
    s4 += ch;
    //查看增容情况
    if (old_capacity != s4.capacity())
    {
      cout << "增容:" << old_capacity <<"->"<< s4.capacity()<< endl;
    }
    old_capacity = s4.capacity();
  }
  cout << s4 << endl << endl;
  return 0;
}

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

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

迭代器

迭代器意义:像string,vector支持[]遍历,但是list,map等等容器不支持[],我们就要用迭代器遍历,所以迭代器是一种统一的使用方式

int main()
{
  string s1 = "Hello c++";
  //迭代器
  string::iterator it = s1.begin();//begin是返回开始位置的迭代器
  while (it != s1.end())//end是返回结束位置的迭代器
  {
    static char tmp = 'a';
    *it++ = tmp++;
  }
  it = s1.begin();
  while (it != s1.end())//end是返回结束位置的迭代器
  {
    cout << *it << " ";
    it++;   
  }
  return 0;
}

反向迭代器

int main()
{
  string s1 = "Hello c++";
  //反向迭代器
  string::reverse_iterator rit = s1.rbegin();
  while (rit != s1.rend())
  {
    cout << *rit << " ";
    rit++;
  }
  return 0;
}

4.string类对象的修改操作

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

注意:

  1. 在string尾部追加字符时,s.push_back© / s.append(1, c) / s += 'c’三种的实现方式差不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
  2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。

int main()
{
  string s;
  s.push_back('h');
  s.push_back('e');
  s.push_back('l');
  s.push_back('l');
  s.push_back('o');
  cout << s << endl;
  s.append(" world");
  cout << s << endl;
  string s2 = "!!!!!!";
  s.append(s2);
  cout << s << endl;
  //但是不巧的是实际中最喜欢用的是+=
  string s3;
  s3 += 'X';
  s3 += "你好";
  s3 += s2;
  cout << s3 << endl;
  //尽量少用insert,因为底层实现是数组,头部或者中间需要挪动数据
  s3.insert(0, "x");
  s3.insert(0,"hhhh");
  cout << s3 << endl;
  //删除
  string s4 = s3;
  string s5 = s3;
  string s6 = s3;
  s4.erase(3, 100);//从第三个开始删除
  s5.erase(3);//从第三个开始删除,一直删完
  s6.erase(); //直接删光
  cout << s4 << endl;
  cout << s5 << endl;
  cout << s6 << endl;
  return 0;
}

int main()
{
  string s("Hello world");
  cout << s << endl;        //这边调的是operator<<(cout,s);
  cout << s.c_str() << endl;//这边调用的是内置类型operator<<(cout,const char*);
  s.resize(20);
  s += "!!!";
  cout << s << endl;
  cout << s.c_str() << endl;
  return 0;
}

int main()
{
  //假设我们需要取文件名的后缀
  string filename = "text.txt.zip";
  size_t pos = filename.rfind('.');
  if (pos != string::npos)
  {
    string suff(filename, pos);
    cout << suff << endl;
  }
  return 0;
}

//取域名
string GetDomain(const string& url)
{
  size_t pos = url.find("://");
  if (pos != string::npos)
  {
    //找到域名的最开始位置
    size_t start = pos + 3;
    //从域名开始的位置向后面找 ’/‘ 
    size_t end = url.find('/', start);
    if (end != string::npos)
    {
      return url.substr(start, end - start);
    }
  }
  //假如没有就返回一个匿名对象
  return string();
}
//取协议
string GetProtocol(const string& url)
{
  size_t pos = url.find("://");
  if (pos != string::npos)
  {
    return url.substr(0, pos);
  }
  //假如没有就返回一个匿名对象
  return string();
}
int main()
{
  //分别取出域名和协议名
  string url1 = "http://www.cplusplus.com/reference/string/string/find/";
  string url2 = "https://juejin.cn/creator/home";
  cout << GetDomain(url1) << endl;
  cout << GetProtocol(url1) << endl;
  cout << GetDomain(url2) << endl;
  cout << GetProtocol(url2) << endl;
  return 0;
}

5.string类非成员函数

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

几题小菜

找字符串中第一个只出现一次的字符

用这题来练手3种遍历

下标+[]

class Solution {
public:
 int firstUniqChar(string s) {
     //26个字母计数数组
     int count[26] = {0};
     int i= 0;
     //遍历计数
     for(i = 0;i<s.size();i++)
     {
         count[s[i]-97]++;
     }
     //找第一个是1的
     for(i = 0;i<s.size();i++)
     {
         if(1 == count[s[i]-97])
         return i;
     }
     return -1;
 }
};
迭代器

class Solution {
public:
 int firstUniqChar(string s) {
     //26个字母计数数组
     int count[26] = {0};
     //迭代器
     string::iterator it = s.begin();
     while(it != s.end())
     {
         count[*it-97]++;
         it++;
     }
     //找第一个是1的
     for(int i = 0;i<s.size();i++)
     {
         if(1 == count[s[i]-97])
         return i;
     }
     return -1;
 }
};
范围for

class Solution {
public:
 int firstUniqChar(string s) {
     //26个字母计数数组
     int count[26] = {0};
     //范围for
    for(auto& e:s)
    {
         count[e-97]++;
    }
     //找第一个是1的
     for(int i = 0;i<s.size();i++)
     {
         if(1 == count[s[i]-97])
         return i;
     }
     return -1;
 }
};

仅仅反转字母

class Solution {
public:
    //判断是否是字母
    bool isletter(const char ch)
    {
        if((ch >= 'a' && ch<='z') ||(ch >= 'A' && ch <='Z'))
        return true;
        return false;
    }
    string reverseOnlyLetters(string s) {
        if(!s.size())
         return s;
       //头尾下标
       int begin = 0,end = s.size()-1;
       while(begin < end)
       {
           while(begin < end && !isletter(s[begin]))
                begin++;
           while(begin < end && !isletter(s[end]))
                end--;
            swap(s[begin],s[end]);
            begin++;
            end--;
       }
       return s;   
    }
};

字符串最后一个单词的长度

#include <iostream>
using namespace std;
int main()
{
    string str;
    getline(cin,str);
    size_t pos = str.rfind(' ');
    if(pos != string::npos)
    {
        cout<< str.size()-pos-1<<endl;
    }
    else
    {
        cout<< str.size()<<endl;
    }
    return 0;
}

验证回文串

class Solution {
public:
    bool isPalindrome(string s) {
        //创建两个空字符串
        string str1,str2,str3;        
        //反向迭代器
        string::reverse_iterator rit = s.rbegin();
        while(rit != s.rend())
        {
            if(*rit >= 'A' && *rit <='Z')
                str1 += *rit+32;
            else if(*rit >= 'a' && *rit<='z')
                str1 += *rit;
            else if(*rit >= '0' && *rit<='9')
                str1 += *rit;
            rit++;
        }
        str2 = str1;
        //再来一次反向迭代器
        string::reverse_iterator rt = str2.rbegin();
        while(rt != str2.rend())
           str3 += *rt++;
        if(str3 == str2)
            return true;
        else
            return false;
    }
};

class Solution {
public:
    //判断字母数字
    bool islettername(const char& ch){
        if(ch >= 'a' && ch <= 'z'
        || (ch >= '0' && ch <='9'))
        return true;
        return false;
    }
    bool isPalindrome(string s) {
        //先把s里面大写全部改成小写的
        for(auto& e:s)
        {
            if(e>='A' && e<='Z')
            e+=32;
        }
        int begin = 0;
        int end = s.size()-1;
        while(begin < end)
        {
            while(begin < end && !islettername(s[begin]))
            begin++;
            while(begin < end && !islettername(s[end]))
            end--;
            if(s[begin] == s[end])
            {
                 begin++; end--;
            }
            else
            return false;
        }
        return true;
    }
};

字符串相加

class Solution {
public:
    string addStrings(string num1, string num2) {
        //两个下标
        int end1 = num1.size()-1,end2 = num2.size()-1;
        //计算后的对象
        string ansStr;
        //进位
        int carry = 0;
        while(end1>=0 || end2>=0)
        {
            int n1 = 0;
            if(end1 >= 0){
                n1 = num1[end1] - '0';
                end1--;
            }
            int n2 = 0;
            if(end2 >= 0){
                n2 = num2[end2] - '0';
                end2--;
            }
            //两个位置开始相加
            int ret = n1+n2+carry;
            if(ret > 9){
                ret -= 10;
                carry = 1;
            }
            else
                carry = 0;
            //这是就准备插字符
            ansStr.insert(0,1,ret+'0');
        }
        //插最后一个进位的
        if(carry)
        ansStr.insert(0,1,carry+'0');
        return ansStr;
    }
};

实际上我们可以看到提交时间看到我们时间复杂度不行,那是因为我们头插了insert了,字符串越长,挪动的就越恶心,也就效率越低,所以我就直接尾插,到最后再来个逆置reverse就行了,这时候就看我们选用的接口了,基本一题都有好几种解法

class Solution {
public:
    string addStrings(string num1, string num2) {
        //两个下标
        int end1 = num1.size()-1,end2 = num2.size()-1;
        //计算后的对象
        string ansStr;
        //进位
        int carry = 0;
        while(end1>=0 || end2>=0)
        {
            int n1 = 0;
            if(end1 >= 0){
                n1 = num1[end1] - '0';
                end1--;
            }
            int n2 = 0;
            if(end2 >= 0){
                n2 = num2[end2] - '0';
                end2--;
            }
            //两个位置开始相加
            int ret = n1+n2+carry;
            if(ret > 9){
                ret -= 10;
                carry = 1;
            }
            else
                carry = 0;
            //这是就准备插字符  我们这就直接尾插
            ansStr += (ret +'0');
        }
        //插最后一个进位的
        if(carry)
        ansStr += (carry +'0');
        //然后逆置就行
        reverse(ansStr.begin(),ansStr.end());
        return ansStr;
    }
};


目录
相关文章
|
16小时前
|
存储 搜索推荐 C++
【C++高阶(二)】熟悉STL中的map和set --了解KV模型和pair结构
【C++高阶(二)】熟悉STL中的map和set --了解KV模型和pair结构
|
16小时前
|
设计模式 C语言 C++
【C++进阶(六)】STL大法--栈和队列深度剖析&优先级队列&适配器原理
【C++进阶(六)】STL大法--栈和队列深度剖析&优先级队列&适配器原理
|
16小时前
|
存储 缓存 编译器
【C++进阶(五)】STL大法--list模拟实现以及list和vector的对比
【C++进阶(五)】STL大法--list模拟实现以及list和vector的对比
|
16小时前
|
算法 C++ 容器
【C++进阶(四)】STL大法--list深度剖析&list迭代器问题探讨
【C++进阶(四)】STL大法--list深度剖析&list迭代器问题探讨
|
1天前
|
存储 算法 C语言
c++的学习之路:9、STL简介与string(1)
c++的学习之路:9、STL简介与string(1)
8 0
|
4天前
|
存储 安全 C语言
【C++】string类
【C++】string类
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
6天前
|
编译器 C++
标准库中的string类(上)——“C++”
标准库中的string类(上)——“C++”
|
12天前
|
存储 算法 C++
【C++初阶】STL详解(九) priority_queue的使用与模拟实现
【C++初阶】STL详解(九) priority_queue的使用与模拟实现
20 0
|
12天前
|
存储 算法 编译器
【C++初阶】STL详解(三)vector的介绍与使用
【C++初阶】STL详解(三)vector的介绍与使用
34 0

热门文章

最新文章