C 學習筆記之MyString的實現和迭代器

2021-09-17 00:23:49 字數 2325 閱讀 6073

mystring類

迭代器的特點:遍歷所有容器的方法都是一樣的,通過begin和end方法實現

class cmystring

else

}~cmystring()

cmystring(const cmystring &str)

cmystring(cmystring &&str)

// str1 = str2.operator=(str3);

cmystring& operator=(const cmystring &str)

cmystring& operator=(cmystring &&str)

bool operator>(const cmystring &str)const

bool operator<(const cmystring &str)const

bool operator==(const cmystring &str)const

int length()const

char& operator(int index)

const char* c_str()const

// cmystring::iterator

**// 實現cmystring容器的迭代器**

class iterator

bool operator!=(const iterator &it)

void operator++()

char& operator*()

// char a = *it; *it='6';

private:

char *_ptr;

}; // 容器的begin和end方法,分別返回

iterator begin()

iterator end()

private:

char *mptr;

friend ostream& operator<<(ostream &out, const cmystring &str);

friend cmystring operator+(const cmystring &l, const cmystring &r);

};cmystring operator+(const cmystring &l, const cmystring &r)

// cmystring str1 = str2 + str3;

// cmystring str1; str1= str2 + str3;

ostream& operator<<(ostream &out, const cmystring &str)

stl六大元件:

1、容器(containers):各種資料結構,如vector,list,deque,set,map,用來存放資料,stl容器是一種class template,就體積而言,這一部分很像冰山載海面的比率。

2、演算法(algorithms):各種常用演算法如sort,search,copy,erase,從實現的角度來看,stl演算法是一種function templates。

3、迭代器(iterators):扮演容器與演算法之間的膠合劑,是所謂的「泛型指標」,共有五種型別,以及其它衍生變化,從實現的角度來看,迭代器是一種將:operators*,operator,operator++,operator–等相關操作予以過載的class template。所有stl容器都附帶有自己專屬的迭代器——是的,只有容器設計者才知道如何遍歷自己的元素,原生指標(native pointer)也是一種迭代器。

4、仿函式(functors):行為類似函式,可作為演算法的某種策略(policy),從實現的角度來看,仿函式是一種過載了operator()的class 或 class template。一般函式指標可視為狹義的仿函式。

5、配接器(介面卡)(adapters):一種用來修飾容器(containers)或仿函式(functors)或迭代器(iterators)介面的東西,例如:stl提供的queue和stack,雖然看似容器,其實只能算是一種容器配接器,因為 它們的底部完全借助deque,所有操作有底層的deque**。改變functor介面者,稱為function adapter;改變container介面者,稱為container adapter;改變iterator介面者,稱為iterator

adapter。配接器的實現技術很難一言蔽之,必須逐一分析。

6、分配器(allocators):負責空間配置與管理,從實現的角度來看,配置器是乙個實現了動態空間配置、空間管理、空間釋放的class template。

-----------來自《stl原始碼剖析》

C 學習筆記之容器

list 和 vector 2者都屬於容器,但list只有雙向迭代器,而vector卻有隨機訪問迭代器 迭代器的種類 前向迭代器 forward iterator 可對迭代器進行 操作雙向迭代器 bidirectional iterator 可對迭代器進行 和 操作隨機訪問迭代器 random ac...

C 學習筆記之異常

程式執行中需要處理異常 異常處理方法一 異常處理方法二 c 異常處理機制 異常處理基礎 例子1 除數為零的異常處理 ex17 1.cpp 除數為零的異常例子 include include using namespace std 定義異常類myexception class myexception ...

C 學習筆記之 引用

先宣告一下,這裡的內容大多是 c 程式設計思想 中的內容,我最近在學習c 覺得裡面的很多話不錯,另外例子也都自己實驗了一番,有些現象很有趣,希望與大家分享。引用 reference 就像能自動地被編譯器間接引用的常量型指標。常量型指標的含義就是常量修飾指標,即指的地方不變,但所指地方的內容可以改變。...