該vector只能容納標准庫中string類,
直接上代碼了,StrVec.h文件內容為:
1 #ifndef STRVEC_H 2 #define STRVEC_H 3 4 #include<iostream> 5 #include<string> 6 #include<memory> 7 using namespace std; 8 class StrVec{ 9 public: 10 // 默認構造函數 11 StrVec():elements(nullptr),first_free(nullptr),cap(nullptr) 12 { 13 14 } 15 //拷貝構造函數 16 StrVec(const StrVec& ); 17 //拷貝賦值運算符 18 StrVec& operator=(const StrVec&); 19 ~StrVec(); 20 void push_back(const string&); 21 size_t size() const { return first_free - elements ; } 22 size_t capacity() const { return cap - elements ;} 23 string* begin() const { return elements ;} 24 string* end() const { return first_free ;} 25 26 27 28 private: 29 static allocator<string> alloc; // 分配元素 30 // 被添加的元素的函數使用 31 void chk_n_alloc() 32 { 33 if( size() == capacity() ) 34 reallocate(); 35 37 } 38 // 工具函數,被拷貝構造函數、賦值運算符和析構函數所使用 39 pair<string* ,string*> alloc_n_copy(const string* ,const string* ); 40 41 45 void free(); 46 void reallocate(); 47 string* elements; // 指向數組首元素的指針 48 string* first_free; // 指向數組第一個空閑元素的指針 49 string* cap; // 指向數組尾后的指針 50 51 52 }; 53 59 #endif
StrVec.cpp文件內容為:
1 #include "StrVec.h" 2 3 std::allocator<string> StrVec::alloc; 4 5 void StrVec::push_back( const string& s ) 6 { 7 chk_n_alloc(); // 確保有空間容納新元素 8 // first_free指向的元素中構造s的副本 9 alloc.construct(first_free++,s) ; 10 11 12 } 13 pair<string* ,string* > StrVec::alloc_n_copy(const string* b, const string* e ) 14 { 15 auto data = alloc.allocate(e-b); 16 return make_pair(data , uninitialized_copy(b,e,data) ); 17 18 19 } 20 void StrVec::free() 21 { 22 // 不能傳遞給deallcoate一個空指針 23 if( elements) 24 { 25 for(auto p = first_free ; p != elements ; ) 26 alloc.destroy(--p); 27 alloc.deallocate(elements,cap-elements) ; 28 } 29 30 31 } 32 StrVec& StrVec::operator=( const StrVec& rhs ) 33 { 34 auto data = alloc_n_copy(rhs.begin() , rhs.end() ); 35 free() ; 36 elements = data.first ; 37 first_free= cap=data.second; 38 39 return *this ; 40 41 } 42 void StrVec::reallocate() 43 { 44 // 我們將分配當前大小兩倍的內存空間; 45 auto newcapacity = size() ? 2*size() :1 ; 46 //分配新內存 47 auto newdata = alloc.allocate( newcapacity ) ; 48 49 auto dest=newdata ; 50 auto elem = elements ; 51 for(size_t i=0; i != size() ; i++) 52 alloc.construct(dest++,std::move( *elem++) ); 53 free(); 54 elements = newdata; 55 first_free = dest ; 56 cap = elements+ newcapacity ; 57 58 59 } 60 StrVec::~StrVec() 61 { 62 free(); 63 }
測試代碼為maintest.cpp
1 #include "StrVec.h" 2 3 int main() 4 { 5 StrVec vec1; 6 vec1.push_back("ok1"); 7 vec1.push_back("ok2"); 8 9 auto begin = vec1.begin(); 10 auto end= vec1.end(); 11 12 while( begin != end ) 13 { 14 cout<<*begin<<endl; 15 // cout<<endl; 16 begin++; 17 18 } 19 22 return 0; 23 }