STL::string简单介绍

发布于:2024-04-25 ⋅ 阅读:(17) ⋅ 点赞:(0)

目录

1、什么是STL

STL6大组件:仿函数、算法、容器、空间配置器、迭代器、配接器

推荐文档(必须学会看文档)

2、string常用接口

 a、初始化


1、什么是STL


标准模板库 STL(Standard Template Library),主要是数据结构和算法的框架,是模板库的一部分,STL是一个规范,是一个实现要求,但是并没有要求实现细节.

STL6大组件:仿函数、算法、容器、空间配置器、迭代器、配接器

推荐文档(必须学会看文档)

string - C++ Reference (cplusplus.com)icon-default.png?t=N7T8https://legacy.cplusplus.com/reference/string/string/?kw=string

2、string常用接口

 a、初始化

哎呀,这部分,再写一遍很没有必要,所以就不写了。毕竟文档介绍的已经足够清晰,不会就查看文档,单词不会就查。主要的是要懂得底层的实现,懂得底层实现的细节,就能够更好的使用。而不仅仅只是一个接口工程师。
string - C++ Reference (cplusplus.com)icon-default.png?t=N7T8https://legacy.cplusplus.com/reference/string/string/?kw=string

string提供的接口非常多,也很冗余。但是不影响,只要用主要的几个就好。

返回值不同不构成函数重载

3、string底层简单实现

#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<iostream>
#include<assert.h>
#include<string.h>
using namespace std;

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;
        typedef const char* const_iterator;

    public:

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

        //s1("xxx")
        string(const char* str = "")
        {
            _size = strlen(str);
            _capacity = _size;
            _str = new char[_capacity + 1];
            strcpy(_str,str);
        }

        //s2(s1)拷贝
        string(const string& s) 
        {
           /* _size = s._size;
            _capacity = _size;
            _str = new char[_capacity + 1];
            strcpy(_str,s._str);*/
            //这里的将s1交s2,同理,也可以直接使用swap交换
            //但是s是一个const,需要拷贝一份非const
            string tmp(s._str);
            swap(tmp);

        }
        //s2 = s1
        string& operator=( string& s)
        {
            /*_size = s._size;
            _str = new char[_size];
            strcpy(_str,s._str);
            _capacity = s._capacity;*/
            string tmp(s);
            swap(tmp);
            return  *this;
        }

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

      const  char* c_str()const
        {

            return _str;
        }

            //

            // iterator

        iterator begin()
        {
            return _str;
        }

        iterator end()
        {
            return _str + _size;
        }

        const_iterator begin() const
        {
            return _str;
        }

        const_iterator end() const
        {
            return _str + _size;
        }

      const  char& operator[]( size_t pos)const
        {
            assert(pos < _size);
            return _str[pos];
        }


        char& operator[]( size_t pos)
        {
            assert(pos < _size);
            return _str[pos];
        }


            /

            //modify

        string& push_back(char c)
        {
          /*  if (_size == _capacity )
            {
                char* tmp = new char[_capacity = _capacity == 0 ? 4 : _capacity * 2];
            }

            _str[_size] = c;
            ++_size;
          */
            insert(_size,c);
            return *this;
        }

     
             string& operator+=(char c)
             {
                 insert(_size,c);
                 return *this;

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

        string& append(const char* str)
        {
            insert(_size,str);
            return *this;
        }


        void clear()
        {
            delete[] _str;
            _capacity = _size = 0;
            _str = nullptr;
        }

        ///
        // capacity

        size_t size()const
        {
            return _size;
        }

        size_t capacity()const
        {
            return _capacity;
        }

        bool empty()const
        {
            return _size == 0;
        }

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

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

            }
        }


        /

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

        size_t find(char c) const
        {
            size_t  i = 0;
            while (i < _size)
            {
                if (_str[i] == c)
                {
                    return i;
                }
                ++i;
            }
        }

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

        size_t find(const char* s) const
        {
            char* cur = strstr(this->_str,s);
            size_t len = cur - _str;
            return len;
        }

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

        size_t insert(size_t pos, char c)
        {
            assert(pos <= _size );

            if (_size <=  _capacity )
            {
               //char* tmp = new char[_capacity == 0 ? 4 : _capacity * 2];//扩容两倍
                reserve(_capacity == 0 ? 4 : _capacity * 2);
            }

            size_t end = _size + 1;//把\0也往后移动
            while(end > pos)//当end到pos下一个位置,正好把pos位置往后移动
            {
                _str[end] = _str[end - 1];
                --end;
            }
            _str[pos] = c;
            _size++;
            return pos;
        }

        void insert(size_t pos, const char* str)
        {
            assert(pos <= _size);
            if (strlen(str ) + _size > _capacity)
            {
                reserve(_size + strlen(str));
            }

            //往后移动len位置,插入str
            size_t len = strlen(str);
            size_t end = len + _size;
            while (end >= pos + len )
            {
                _str[end] = _str[end - len];
                --end;
            }
            
            //不能把\0粘贴进来
            strncpy(_str + pos, str,len);
            _size += len;
        }



        // 删除pos位置上的元素,并返回该元素的下一个位置
        size_t erase(size_t pos, size_t len  = 1)
        {
            assert(pos < _size);
            //删除pos位置以后的值
            //如果n等于超过size,删完,不管
            //小于,往前挪动覆盖即可
            if ( len  >= _size - pos )
            {
                _str[len] = '\0';
                _size = pos;
            }
            else
            {
                //从pos位置开始,往后len个位置,往前覆盖
                strcpy(_str + pos, _str + pos + len);
                _size -= len;
            }
            return pos + 1;
        }


        void print()
        {
            for (auto e : *this)
            {
                cout << e ;
            }
            cout << endl;
        }

        public:
            static const int npos;//声明

    private:

        char* _str;

        size_t _capacity;

        size_t _size;

    };

    //创建
    const int string::npos = -1;

    //relational operators直接利用strcmp函数返回值,而不是自己遍历对比

    bool operator<(const string& s1, const string& s2)
    {
        int ret =  strcmp(s1.c_str(), s2.c_str()) ;
        return ret < 0;
    }

    bool operator>(const string& s1, const string& s2)
    {
        int ret = strcmp(s1.c_str(), s2.c_str());
        return ret > 0;
    }

    bool operator<=(const string& s1, const string& s2)
    {
        return !(s1 > s2);
    }

    bool operator>=(const string& s1, const string& s2)
    {
        return !(s1 < s2);
    }

    bool operator==(const string& s1, const string& s2)
    {
       int ret =  strcmp(s1.c_str(), s2.c_str()) ;
       return ret == 0;
    }

    bool operator!=(const string& s1, const string& s2)
    {
        return !(s1 == s2);
    }



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

     istream& operator>>(istream& _cin, bit::string& s)
    {
         
         for (size_t i = 0; i<s.size();++i)
         {
             _cin >> s._str[i];
         }
         return _cin;
    }



    void test1()
    {
        string s0;
        string s1("hello world");
        const string s2("hello Linux");
        s0 = s1;

       const  string s3 = s2;

      for (auto e : s3)
      {
          cout << e;
      }
      cout << endl;
    }

    void test2()
    {
        string s("hello world");
        s.reserve(5);
        cout << s.capacity() << endl;;
        s.reserve(20);
        cout << s.capacity() << endl;
        s.print();
    }


    void test3()
    {
        string s("hello world");
        //s.resize(5);
        //s.print();
        //cout << s.size() << endl;
        s.resize(30,'x');
        s.print();
        cout << s.size() << endl;
        cout << s[29] << endl;
    }

    void test4()
    {
        string s1("abc");
        string s2("def");
        cout << (s1 == s2) << endl;
        cout << (s1 != s2) << endl;
        cout << (s1>s2) << endl;
        cout << (s1 <= s2) << endl;
        cout << (s1 >= s2) << endl;
    }

    void test5()
    {
        string s1("abcxxxxxxxxxxxxxxxxxxxxx");
       s1.erase(1,100);
       // s1.erase(1);
        s1.print();
    }

    void test6()
    {
        string s("hello world");
        //s.insert(11,"xxxxx");
        s.insert(11,"abbbb");
        cout << s.capacity() << endl;
        cout << s.size() << endl;

       s.print();
    
    }

    void test7()
    {
        string s1("aaabbbccc");
        //size_t add = s1.find('b');
        size_t add = s1.find("ccc");
        cout << add << endl;
    }

    void test8()
    {
        string s("hello world");
        s.push_back('a');
        s.append("xxxx");
        s += 'w';
        s += "oooooo";
        
        //cout << s << endl;
        s.print();
    }

    void test9 ()
    {
        //string s("hello world ");
        //cout << s;
        string s1;
        //int a;
        //cin >> a;
        //cout << a;

        //"hello" >> s1.c_str;
        cout<<s1;
    }



};