【C++】C++ STL探索:Vector使用与背后底层逻辑(三)

简介: 【C++】C++ STL探索:Vector使用与背后底层逻辑

【C++】C++ STL探索:Vector使用与背后底层逻辑(二)https://developer.aliyun.com/article/1617342


三、vector.h

#pragma once
#include <assert.h>
#include <iostream>
#include <algorithm>
using namespace std;
namespace bit
{
    template<class T>
        class vector
        {
            public:
            typedef  T*  iterator;
            typedef const T* const_iterator;
            iterator begin()
            {
                return _start;
            }
            iterator end()
            {
                return _finish;
            }
            const_iterator begin() const
            {
                return _start;
            }
            const_iterator end() const
            {
                return _finish;
            }
            //构造函数
            //无参构造
            vector()
            {}
            //有参构造
            //.....
            //析构
            ~vector()
            {
                delete[]_start;
                _start = nullptr;
                _finish = _end_of_storage = nullptr;
            }
            //vector<int> v1={1,2,3,4,5,6};
            vector(initializer_list<T> il)
            {
                reserve(il.size());
                for (auto& e : il)
                {
                    push_back(e);
                }
            }
            //拷贝构造
            //v2(v1)
            vector(const vector<T>& v)
            {
                //需要开一样大的空间
                reserve(v.capacity());
                for (auto& e : v)
                {
                    push_back(e);
                }
            }
            //v2 = v1;
            vector<T>& operator=(vector<T> v)
            {
                swap(v);
                return *this;
            }
            //通过下标访问
            //并且不知道会返回什么具体的类型
            T& operator[](size_t pos)
            {
                //不能等于size(),指向\0
                assert(pos < size());
                return _start[pos];
            }
            const T& operator[](size_t pos) const
            {
                assert(pos < size());
                return _start[pos];
            }
            //交换
            void swap(vector<T>& v)
            {
                std::swap(_start, v._start);
                std::swap(_start, v._start);
                std::swap(_start, v._start);
            }
            //得到当前元素空间信息
            //指针-指针
            size_t size() const
            {
                return _finish - _start;
            }
            size_t capacity() const
            {
                return _end_of_storage - _start;
            }
            //扩容
            //第一个问题,迭代器失效
            //void reserve(size_t n)
            //{
            //  if (n > capacity())
            //  {
            //    T* tmp = new T[n];
            //    memcpy(tmp, _start, size(T) * n);
            //    delete[] _start;
            //    _start = tmp;
            //    _finish =  tmpt + size();
            //    _end_of_storage =  tmp + n;
            //  }
            //}
            改良
            第二个问题,当T为自定义类型,就是浅拷贝,但是还是指向同一块空间
            //void reserve(size_t n)
            //{
            //  if (n > capacity())
            //  {
            //    size_t old_size = size();
            //    T* tmp = new T[n];
            //    memcpy(tmp, _start, size(T) * n);
            //    delete[] _start;
            //    _start = tmp;
            //    _finish =  tmp + old_size;
            //    _end_of_storage =  tmp + n;
            //  }
            //}
            正确写法
            void reserve(size_t n)
            {
                if (n > capacity())
                {
                    size_t old_size = size();
                    T* tmp = new T[n];
                    //memcpy(tmp, _start, size(T) * n);
                    for (size_t i = 0; i < old_size; i++)
                    {
                        tmp[i] = _start[i];
                    }
                    delete[] _start;
                    _start = tmp;
                    _finish = tmp + old_size;
                    _end_of_storage = tmp +n ;
                }
            }
            //vector的迭代区间
            //函数模板
            template<class InputIterator>
                vector(InputIterator fist, InputIterator last)
            {
                while (fist != last)
                {
                    push_back(*fist);
                    ++fist;
                }
            }
            //初始化 构造
            vector(size_t n, const T& val = T())
            {
                reserve(n);
                for (size_t i = 0; i < n; i++)
                {
                    push_back(val);
                }
            }
            vector(int n, const T& val = T())
            {
                reserve(n);
                for (int i = 0; i < n; i++)
                {
                    push_back(val);
                }
            }
            //重点实现resize
            void resize(size_t n, const T& val = T())
            {
                //缩容
                if (n <= size())
                {
                    _finish = _start + n;
                }
                else
                {
                    //提前扩容
                    //大于capacity才起作用
                    reserve(n);
                    while (_finish < _start + n)
                    {
                        *_finish = val;
                        _finish++;
                    }
                }
            }
            //核心操作
            void push_back(const T& val )
            {
                insert(end(), val);
            }
            void pop_back()
            {
                /*  assert(!empty());
      _finish--;*/
                //不能--
                erase(end() - 1);
            }
            //判断空
            bool empty()
            {
                return _start == _finish;
            }
            //实现插入操作时,可能会涉及到扩容操作,就有可能出现迭代器失效的可能
            void insert(iterator pos, const T& val )
            {
                assert(_start <= pos);
                assert(pos <= _finish);
                //考虑是否需要扩容
                //说明空间已经满了
                if (_finish == _end_of_storage)
                {
                    size_t len = pos - _start;
                    //这里迭代器失效的问题
                    //不是解决了吗!当时pos没有解决呀!
                    reserve(capacity() == 0 ? 4 : capacity() * 2);
                    pos = _start + len;
                }
                //开始移动数据
                iterator it = _finish - 1;
                while (it >= pos)
                {
                    *(it + 1) = *it;
                    it--;
                }
                *pos = val;
                _finish++;
            }
            //迭代器实现erase
            iterator erase(iterator pos)
            {
                assert(_start <= pos);
                //删除不到_finish这个位置
                assert(pos < _finish);
                iterator it = pos+1;
                //it=pos+1=_finish就是最后一个位置
                while (it <= _finish)
                {
                    *(it - 1) = *(it);
                    it++;
                }
                _finish--;
                return pos;
            }
            private:
            iterator _start=nullptr;
            iterator _finish=nullptr;
            iterator _end_of_storage=nullptr;
        };
    // 函数模板
    template<class T>
        void print_vector(const vector<T>& v)
    {
        //for (size_t i = 0; i < v.size(); i++)
        //{
        //  cout << v[i] << " ";
        //}
        //cout << endl;
        //typename vector<T>::const_iterator it = v.begin();
        auto it = v.begin();
        while (it != v.end())
        {
            cout << *it << " ";
            ++it;
        }
        cout << endl;
        /*for (auto e : v)
    {
      cout << e << " ";
    }
    cout << endl;*/
    }
    void test1()
    {
        vector<int> v;
        v.push_back(12);
        v.pop_back();
        v.push_back(1);
        print_vector(v);
    }
    void test_vector2()
    {
        vector<int> v1(10, 1);
        print_vector(v1);
        vector<int> v2(10u, 1);
        print_vector(v2);
        vector<int> v3(10, 'a');
        print_vector(v3);
    }
    void test_vector3()
    {
        vector<int> v1;
        v1.push_back(1);
        v1.push_back(2);
        v1.push_back(3);
        v1.push_back(4);
        v1.push_back(5);
        v1.push_back(6);
        v1.push_back(7);
        v1.push_back(8);
        print_vector(v1);
        vector<int>::iterator it = v1.begin() + 3;
        v1.insert(it, 40);
        print_vector(v1);
        cout << *it << endl;
    }
    void test_vector4()
    {
        auto x = { 1,2,3,4,5,6 };
        cout << typeid(x).name() << endl;
        cout << sizeof(x) << endl;
    }
    void test_vector5()
    {
        vector<int> v1;
        v1.push_back(1);
        v1.push_back(2);
        v1.push_back(3);
        v1.push_back(4);
        v1.push_back(5);
        v1.push_back(4);
        //std::vector<int>::iterator it = v1.begin();
        vector<int>::iterator it = v1.begin();
        while (it != v1.end())
        {
            if (*it % 2 == 0)
            {
                it=v1.erase(it);
            }
            else
            {
                it++;
            }
        }
        print_vector(v1);
    }
}

以上就是本篇文章的所有内容,在此感谢大家的观看!这里是店小二呀C++笔记,希望对你在学习C++语言旅途中有所帮助!

相关文章
|
7月前
|
编译器 C++ 容器
【c++丨STL】基于红黑树模拟实现set和map(附源码)
本文基于红黑树的实现,模拟了STL中的`set`和`map`容器。通过封装同一棵红黑树并进行适配修改,实现了两种容器的功能。主要步骤包括:1) 修改红黑树节点结构以支持不同数据类型;2) 使用仿函数适配键值比较逻辑;3) 实现双向迭代器支持遍历操作;4) 封装`insert`、`find`等接口,并为`map`实现`operator[]`。最终,通过测试代码验证了功能的正确性。此实现减少了代码冗余,展示了模板与仿函数的强大灵活性。
181 2
|
7月前
|
存储 算法 C++
【c++丨STL】map/multimap的使用
本文详细介绍了STL关联式容器中的`map`和`multimap`的使用方法。`map`基于红黑树实现,内部元素按键自动升序排列,存储键值对,支持通过键访问或修改值;而`multimap`允许存在重复键。文章从构造函数、迭代器、容量接口、元素访问接口、增删操作到其他操作接口全面解析了`map`的功能,并通过实例演示了如何用`map`统计字符串数组中各元素的出现次数。最后对比了`map`与`set`的区别,强调了`map`在处理键值关系时的优势。
352 73
|
8月前
|
存储 缓存 C++
C++ 容器全面剖析:掌握 STL 的奥秘,从入门到高效编程
C++ 标准模板库(STL)提供了一组功能强大的容器类,用于存储和操作数据集合。不同的容器具有独特的特性和应用场景,因此选择合适的容器对于程序的性能和代码的可读性至关重要。对于刚接触 C++ 的开发者来说,了解这些容器的基础知识以及它们的特点是迈向高效编程的重要一步。本文将详细介绍 C++ 常用的容器,包括序列容器(`std::vector`、`std::array`、`std::list`、`std::deque`)、关联容器(`std::set`、`std::map`)和无序容器(`std::unordered_set`、`std::unordered_map`),全面解析它们的特点、用法
C++ 容器全面剖析:掌握 STL 的奥秘,从入门到高效编程
|
8月前
|
算法 编译器 C++
模拟实现c++中的vector模版
模拟实现c++中的vector模版
|
7月前
|
存储 算法 C++
【c++丨STL】set/multiset的使用
本文深入解析了STL中的`set`和`multiset`容器,二者均为关联式容器,底层基于红黑树实现。`set`支持唯一性元素存储并自动排序,适用于高效查找场景;`multiset`允许重复元素。两者均具备O(logN)的插入、删除与查找复杂度。文章详细介绍了构造函数、迭代器、容量接口、增删操作(如`insert`、`erase`)、查找统计(如`find`、`count`)及`multiset`特有的区间操作(如`lower_bound`、`upper_bound`、`equal_range`)。最后预告了`map`容器的学习,其作为键值对存储的关联式容器,同样基于红黑树,具有高效操作特性。
289 3
|
8月前
|
存储 算法 C++
【c++丨STL】priority_queue(优先级队列)的使用与模拟实现
本文介绍了STL中的容器适配器`priority_queue`(优先级队列)。`priority_queue`根据严格的弱排序标准设计,确保其第一个元素始终是最大元素。它底层使用堆结构实现,支持大堆和小堆,默认为大堆。常用操作包括构造函数、`empty`、`size`、`top`、`push`、`pop`和`swap`等。我们还模拟实现了`priority_queue`,通过仿函数控制堆的类型,并调用封装容器的接口实现功能。最后,感谢大家的支持与关注。
399 1
|
8月前
|
存储 算法 C++
深入浅出 C++ STL:解锁高效编程的秘密武器
C++ 标准模板库(STL)是现代 C++ 的核心部分之一,为开发者提供了丰富的预定义数据结构和算法,极大地提升了编程效率和代码的可读性。理解和掌握 STL 对于 C++ 开发者来说至关重要。以下是对 STL 的详细介绍,涵盖其基础知识、发展历史、核心组件、重要性和学习方法。
|
8月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
4月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
96 0
|
4月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
173 0