c 是泛型程序设计语言,c ++中的“泛型编程”是什么意思?
容器
在C ++中,容器是允許您存儲對象的類。 例如,標準庫std::list l是可調整大小的數組,用于存儲某種類型T的對象。為了正式地被認為是容器類,它必須公開某些功能以便于通用編程。 我可以引用C ++標準的確切要求,但在大多數情況下,重要的容器類是標準庫中的容器:std::list、deque、list、map、set和2687499344584115115/2/multiset。
重要要求之一是它們必須允許迭代器訪問。
迭代器
“迭代器”在這里可能意味著兩件事:它是設計模式的名稱,但是在C ++中,它也是該設計模式的特定表達式的名稱。 C ++迭代器是一種類型的類型,它允許使用類似指針的語法遍歷一系列元素。
例如,如果您有一個數組std::list l,則可以使用普通指針作為迭代器:
int* first = a; // create an iterator that points to the beginning of the array
++first; // make the iterator point to the second element
int i = *first; // get the value of the element pointed to by the iterator
int* last = a+10; //create an "end" iterator, one which points one past the end of the array
如果我有一個鏈表,例如std::list l,我可以做很多事情,盡管現在我的迭代器不再只是指針,而是實現為專門用于std::list的類類型:
std::list::iterator first = l.begin(); // create an iterator that points to the beginning of the list
++first; // make the iterator point to the second element
int i = *first; // get the value of the element pointed to by the iterator
std::list::iterator last = l.end(); //create an "end" iterator, one which points one past the end of the list
或帶有向量IIterator:
std::vector::iterator first = v.begin(); // create an iterator that points to the beginning of the vector
++first; // make the iterator point to the second element
int i = *first; // get the value of the element pointed to by the iterator
std::list::iterator last = v.end(); //create an "end" iterator, one which points one past the end of the vector
關于迭代器的重要之處在于,它們為我們提供了遍歷元素序列的統一語法,無論序列如何存儲在內存中(甚至即使存儲在內存中也是如此。可以編寫迭代器以迭代a的內容) 磁盤上的數據庫,或者我們也可以使用迭代器包裝器使流(例如IIterator)看起來也像一系列對象:
std::istream_iterator(std::cin) first;
++first; // make the iterator point to the second element
int i = *first; // get the value of the element pointed to by the iterator
std::list::iterator last; //create an "end" iterator, which marks the end of the stream
盡管因為它包裝了常規的流,但是它是一種更有限的迭代器類型(例如,您不能向后移動,這意味著并非以下所有算法都適用于流迭代器。
現在,考慮到這些迭代器類型中的任何一種,我們可以使用所有旨在與迭代器一起使用的標準庫算法。 例如,要查找序列中值為IIterator的第一個元素:
std::find(first, last, 4); // return the first iterator which equals 4 and which is located in the interval [first, last)
或者我們可以對序列進行排序(不適用于流迭代器):
std::sort(first, last);
或者如果我們編寫一個將int平方的函數,例如:
int square(int i) { return i * i; }
然后我們可以將其應用于整個序列:
// for every element in the range [first, last), apply the square function, and output the result into the sequence starting with first
std::transform(first, last, first, square);
這就是迭代器的優點:它們抽象了容器的詳細信息,因此我們可以對任何序列應用泛型操作。 多虧了迭代器,相同的IIterator或sort實施也可用于鏈接列表和數組,甚至可用于您自己的自制容器類。
通用編程
泛型編程基本上是您的代碼應盡可能通用的想法。 如上面的迭代器示例所示,我們提供了一組類型必須支持的一組通用功能才能被稱為迭代器,然后編寫適用于任何迭代器類型的算法。
將此與傳統的面向對象編程進行比較,在傳統的面向對象編程中,迭代器必須通過繼承某種IIterator接口來“證明”它們是迭代器。 那將阻止我們使用原始指針作為迭代器,因此我們將失去通用性。
在C ++中,使用通用編程,我們不需要官方接口。 我們只是使用模板編寫算法,因此它們接受恰好看起來像迭代器的任何類型,而不管它們在何處,何時以及如何定義,以及它們是否從公共基類或接口派生。
總結
以上是生活随笔為你收集整理的c 是泛型程序设计语言,c ++中的“泛型编程”是什么意思?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux驱动私有数据,linux驱动开
- 下一篇: 余额宝换基金怎么换 余额宝的基金怎么换