STL与泛型编程 week 4 (Boolan)

C++标准库的算法,是什么东西?

从语言层面讲

  • 容器Container是个class template
  • 算法Algorithm是个function template
  • 迭代器Iterator是个class template
  • 仿函数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?

一个简单的打印函数:

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);
}

使用该打印函数的例子:

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()将会创建一个临时的对象. 如该对象为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(); // 此函数协助取出iterator的category, 
                     // 并以此创建一个临时对象.
}

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

评论: 在算法advance中, iterator_category(i)将会创建一个临时的对象. 如该对象为input_iterator_tag, advance调用第一个__advance; 如该对象为forward_iterator_tag / bidirectional_iterator_tag, advance调用第二个__advance; 如该对象为random_access_iterator_tag, 则advance调用第三个__advance.

仿函数

在C++中,有些算法是通过仿函数来实现的,这些仿函数基本都会继承某个类的,例如binary_function<T,T,T> 或者unarg_function<T,T>. 这是因为这些仿函数并不是单独存在的,他们可能只是算法的一部分,需要其他算法进行调用,才能发挥作用, 但是如果是的自己可以被其他函数调用,就需要告知调用者 自己的返回值,参数等特性. 这一点跟容器的traits非常类似,把需要告知算法的信息进行统一的封装.

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,651评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,468评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,931评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,218评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,234评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,198评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,084评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,926评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,341评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,563评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,731评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,430评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,036评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,676评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,829评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,743评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,629评论 2 354

推荐阅读更多精彩内容