STL與泛型編程 week 4 (Boolan)

C++標準庫的算法,是什么東西?

從語言層面講

  • 容器Container是個class template
  • 算法Algorithm是個function template
  • 迭代器Iterator是個class template
  • 仿函數(shù)Functor是個class template
  • 適配器Adapter是個class template
  • 分配器Allocator是個class template
template <typename Iterator>
Algorithm(Iterator itr1, Iterator itr2)
{
  ...
}
template <typename Iterator, typename Cmp>
Algorithm(Iterator itr1, Iterator itr2, Cmp comp)
{
  ...
}

Algorithms 看不見Containers, 對其一無所知; 所以, 它所需要的一切信息都必須從Iterators取得, 而Iterator(由Container供應)必須能夠回答Algorithm的所有提問, 才能搭配該Algorithm的所有操作.

各種容器的iterators有五種不同的iterator_category

struct input_iterator_tag {};
struct output_iterator_tag {};
struct forward_iterator_tag : public input_iterator_tag {};
struct bidirectional_iterator_tag : public input_iterator_tag {};
struct random_access_iterator_tag : public input_iterator_tag {};

如何打印iterator_category?

一個簡單的打印函數(shù):

void _display_category(input_iterator_tag)
{ cout << "input_iterator" << endl;  }
void _display_category(output_iterator_tag)
{ cout << "output_iterator" << endl;  }
void _display_category(forward_iterator_tag)
{ cout << "forward_iterator" << endl;  }
void _display_category(bidirectional_iterator_tag)
{ cout << "bidirectional_iterator" << endl;  }
void _display_category(random_access_iterator_tag)
{ cout << "random_access_iterator" << endl;  }

template <typename I>
void display_category(I itr)
{
  typename iterator_traits<I>::iterator_category cagy;
  _display_category(cagy);
}

使用該打印函數(shù)的例子:

cout << "\ntest_iterator_category()..........\n";

display_category(array<int, 10>::iterator());
display_category(vector<int>::iterator());
display_category(list<int>::iterator());
display_category(forward<int>::iterator());
display_category(deque<int>::iterator());

各種容器的iterators的iterator_category的typeid

template <typename I>
void display_category(I itr)
{
  // The output depends on library implementation.
  // The particular representation pointed by
  // returned value is implementation defined,
  // and may or may not be different for different types.
  cout << "typeid(itr).names=" << typeid(itr).name() << endl;
}

關于運行時類型識別RTTI (摘自C++ Primer):

Run-time type identification (RTTI) is provided through two operators: 1. The typeid operator, which returns the type of a given expression; 2. The dynamic_cast operator, which safely converts a pointer or reference to a base type into a pointer or reference to a derived type. When applied to pointers or references to types that have virtual functions, these operators use the dynamic type of the object to which the pointer or reference is bound.
These operators are useful when we have a derived operation that we want to perform through a pointer or reference to a base-class object and it is not possible to make that operation a virtual function. Ordinarily, we should use virtual functions if we can. When the operation is virtual, the compiler automatically selects the right function according to the dynamic type of the object.
However, it is not always possible to define a virtual. If we cannot use a virtual, we can use one of the RTTI operators. On the other hand, using these operators is more error-prone than using virtual member functions: The programmer must know to which type the object should be cast and must check that the cast was performed successfully.

iterator_category對算法的影響

第一個例子 distance算法:

template <class InputIterator>
inline iterator_traits<InputIterator>::difference_type
__distance(InputIterator first, InputIterator last, input_iterator_tag) {
  iterator_traits<InputIterator>::difference_type n = 0;
  while (first != last) {
    ++first; ++n;
  }
  return n;
}
template <class RandomAccessIterator>
inline iterator_traits<RandomAccessIterator first, RandomAccessIterator last, random_access_iterator_tag> {
  return last - first;
}
// ----------------------------------------------------------------------
template <class InputIterator>
inline iterator_traits<InputIterator>::difference_type
distance(InputIterator first, InputIterator last) {
  typedef typename
    iterator_traits<InputIterator>::iterator_category category;
  return __distance(first, last, category());
}

評論: 在算法distance中, category()將會創(chuàng)建一個臨時的對象. 如該對象為input_iterator_tag / forward_iterator_tag / bidirectional_iterator_tag, distance調用第一個__distance; 如該對象為random_access_iterator_tag, 則distance調用第二個__distance.

第二個例子 advance算法:

template <class InputIterator, class Distance>
inline void __advance(InputIterator &i, Distance n, input_iterator_tag) {
  while (n--) ++i;
}
template <class BidirectionalIterator, class Distance>
inline void __advance(BidirectionalIterator &i, Distance n, bidirectional_iterator_tag) {
  if (n >= 0) while (n--) ++i;
  else while (n++) --i;
}
template <class RandomAccessIterator, class Distance>
inline void __advance(RandomAccessIterator &i, Distance n, random_access_iterator_tag) {
  i += n;
}
// -------------------------------------------------------------------------
template <class Iterator>
inline typename iterator_traits<Iterator>::iterator_category
iterator_category(const Iterator&) {
  typedef typename iterator_traits<Iterator>::iterator_category category;
  return category(); // 此函數(shù)協(xié)助取出iterator的category, 
                     // 并以此創(chuàng)建一個臨時對象.
}

template <class InputIterator, class Distance>
inline void advance(InputIterator &i, Distance n) {
  __advance(i, n, iterator_category(i));
}

評論: 在算法advance中, iterator_category(i)將會創(chuàng)建一個臨時的對象. 如該對象為input_iterator_tag, advance調用第一個__advance; 如該對象為forward_iterator_tag / bidirectional_iterator_tag, advance調用第二個__advance; 如該對象為random_access_iterator_tag, 則advance調用第三個__advance.

仿函數(shù)

在C++中杯拐,有些算法是通過仿函數(shù)來實現(xiàn)的,這些仿函數(shù)基本都會繼承某個類的歪今,例如binary_function<T,T,T> 或者unarg_function<T,T>. 這是因為這些仿函數(shù)并不是單獨存在的,他們可能只是算法的一部分颜矿,需要其他算法進行調用寄猩,才能發(fā)揮作用, 但是如果是的自己可以被其他函數(shù)調用,就需要告知調用者 自己的返回值或衡,參數(shù)等特性. 這一點跟容器的traits非常類似焦影,把需要告知算法的信息進行統(tǒng)一的封裝.

template <class Arg, class Result>
struct unarg_function{
    typedef    Arg    argument_type;
    typedef    Result    result_type;
};

template <class Arg1, class Arg2, class Result>
struct binarg_function {
    typedef    Arg1    first_argument_type;
    typedef    Arg2    second_argument_type;
    typedef    Result    result_type;
};

Reverse Iterator

摘自C++ Primer:

A reverse iterator is an iterator that traverses a container backward, from the last element toward the first. A reverse iterator inverts the meaning of increment (and decrement). Incrementing (++it) a reverse iterator moves the iterator to the previous element; derementing (--it) moves the iterator to the next element.
The containers, aside from forward_list, all have reverse iterators. We obtain a reverse iterator by calling the rbegin, rend, crbegin, and crend members. These members return reverse iterators to the last element in the container and one “past” (i.e., one before) the beginning of the container. As with ordinary iterators, there are both const and nonconst reverse iterators.
The following picture illustrates the relationship between these four iterators on a hypothetical vector named vec.

Comparing begin/cend and rbegin/crend Iterators

Insert Iterators

摘自C++ Primer:

An inserter is an iterator adaptor that takes a container and yields an iterator that adds elements to the specified container. When we assign a value through an insert iterator, the iterator calls a container operation to add an element at a specified position in the given container.
There are three kinds of inserters. Each differs from the others as to where elements are inserted:

  • back_inserter creates an iterator that uses push_back.
  • front_inserter creates an iterator that uses push_front.
  • inserter creates an iterator that uses insert. This function takes a second argument, which must be an iterator into the given container. Elements are inserted ahead of the element denoted by the given iterator.
  • 使用inserter的返回值是什么? (摘自C++ Primer)

It is important to understand that when we call inserter(c, iter), we get an iterator that, when used successively, inserts elements ahead of the element originally denoted by iter. That is, if it is an iterator generated by inserter, then an assignment such as *it=val; behaves as the following code:

it = c.insert(it, val); // it points to the newly added element
++it; // increment it so that it denotes the same element as before

X適配器: istream_iterator 和 ostream_iterator

基本概念(摘自C++ Primer):

Even though the iostream types are not containers, there are iterators that can be used with objects of the IO types. An istream_iterator reads an input stream, and an ostream_iterator writes an output stream. These iterators treat their corresponding stream as a sequence of elements of a specified type. Using a stream iterator, we can use the generic algorithms to read data from or write data to stream objects.

istream_iterator的使用(摘自C++ Primer):

When we create a stream iterator, we must specify the type of objects that the iterator will read or write. An istream_iterator uses >> to read a stream. Therefore, the type that an istream_iterator reads must have an input operator defined. When we create an istream_iterator, we can bind it to a stream. Alternatively, we can default initialize the iterator, which creates an iterator that we can use as the off-the-end value.

ostream_iterator的使用(摘自C++ Primer):

An ostream_iterator can be defined for any type that has an output operator (the << operator). When we create an ostream_iterator, we may (optionally) provide a second argument that specifies a character string to print following each element. That string must be a C-style character string (i.e., a string literal or a pointer to a null-terminated array). We must bind an ostream_iterator to a specific stream. There is no empty or off-the-end ostream_iterator.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子舱殿,更是在濱河造成了極大的恐慌蕊苗,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件控轿,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機柄瑰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來剪况,“玉大人教沾,你說我怎么就攤上這事∫攵希” “怎么了授翻?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長孙咪。 經(jīng)常有香客問我堪唐,道長,這世上最難降的妖魔是什么翎蹈? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任淮菠,我火速辦了婚禮,結果婚禮上荤堪,老公的妹妹穿的比我還像新娘合陵。我一直安慰自己枢赔,他們只是感情好,可當我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布拥知。 她就那樣靜靜地躺著踏拜,像睡著了一般。 火紅的嫁衣襯著肌膚如雪举庶。 梳的紋絲不亂的頭發(fā)上执隧,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天,我揣著相機與錄音户侥,去河邊找鬼镀琉。 笑死,一個胖子當著我的面吹牛蕊唐,可吹牛的內容都是我干的屋摔。 我是一名探鬼主播,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼替梨,長吁一口氣:“原來是場噩夢啊……” “哼钓试!你這毒婦竟也來了?” 一聲冷哼從身側響起副瀑,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤弓熏,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后糠睡,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體挽鞠,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年狈孔,在試婚紗的時候發(fā)現(xiàn)自己被綠了信认。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡均抽,死狀恐怖嫁赏,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情油挥,我是刑警寧澤潦蝇,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站喘漏,受9級特大地震影響护蝶,放射性物質發(fā)生泄漏。R本人自食惡果不足惜翩迈,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一持灰、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧负饲,春花似錦堤魁、人聲如沸喂链。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽椭微。三九已至,卻和暖如春盲链,著一層夾襖步出監(jiān)牢的瞬間蝇率,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工刽沾, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留本慕,地道東北人。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓侧漓,卻偏偏與公主長得像锅尘,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子布蔗,可洞房花燭夜當晚...
    茶點故事閱讀 44,614評論 2 353

推薦閱讀更多精彩內容