C++中STL中简单的Vector的实现

时间:2023-07-17 08:28:38

该vector只能容纳标准库中string类,

直接上代码了,StrVec.h文件内容为:

 #ifndef STRVEC_H
#define STRVEC_H #include<iostream>
#include<string>
#include<memory>
using namespace std;
class StrVec{
public:
// 默认构造函数
StrVec():elements(nullptr),first_free(nullptr),cap(nullptr)
{ }
//拷贝构造函数
StrVec(const StrVec& );
//拷贝赋值运算符
StrVec& operator=(const StrVec&);
~StrVec();
void push_back(const string&);
size_t size() const { return first_free - elements ; }
size_t capacity() const { return cap - elements ;}
string* begin() const { return elements ;}
string* end() const { return first_free ;} private:
static allocator<string> alloc; // 分配元素
// 被添加的元素的函数使用
void chk_n_alloc()
{
if( size() == capacity() )
reallocate(); }
// 工具函数,被拷贝构造函数、赋值运算符和析构函数所使用
pair<string* ,string*> alloc_n_copy(const string* ,const string* ); void free();
void reallocate();
string* elements; // 指向数组首元素的指针
string* first_free; // 指向数组第一个空闲元素的指针
string* cap; // 指向数组尾后的指针 }; #endif

StrVec.cpp文件内容为:

 #include "StrVec.h"

 std::allocator<string> StrVec::alloc;

 void StrVec::push_back( const string& s )
{
chk_n_alloc(); // 确保有空间容纳新元素
// first_free指向的元素中构造s的副本
alloc.construct(first_free++,s) ; }
pair<string* ,string* > StrVec::alloc_n_copy(const string* b, const string* e )
{
auto data = alloc.allocate(e-b);
return make_pair(data , uninitialized_copy(b,e,data) ); }
void StrVec::free()
{
// 不能传递给deallcoate一个空指针
if( elements)
{
for(auto p = first_free ; p != elements ; )
alloc.destroy(--p);
alloc.deallocate(elements,cap-elements) ;
} }
StrVec& StrVec::operator=( const StrVec& rhs )
{
auto data = alloc_n_copy(rhs.begin() , rhs.end() );
free() ;
elements = data.first ;
first_free= cap=data.second; return *this ; }
void StrVec::reallocate()
{
// 我们将分配当前大小两倍的内存空间;
auto newcapacity = size() ? *size() : ;
//分配新内存
auto newdata = alloc.allocate( newcapacity ) ; auto dest=newdata ;
auto elem = elements ;
for(size_t i=; i != size() ; i++)
alloc.construct(dest++,std::move( *elem++) );
free();
elements = newdata;
first_free = dest ;
cap = elements+ newcapacity ; }
StrVec::~StrVec()
{
free();
}

测试代码为maintest.cpp

 #include "StrVec.h"

 int main()
{
StrVec vec1;
vec1.push_back("ok1");
vec1.push_back("ok2"); auto begin = vec1.begin();
auto end= vec1.end(); while( begin != end )
{
cout<<*begin<<endl;
// cout<<endl;
begin++; } return ;
}