STL与泛型编程 week 4 (Boolan)

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

从语言层面讲

  • 容器Container是个class template
  • 算法Algorithm是个function template
  • 迭代器Iterator是个class template
  • 仿函数Functor是个class template
  • 适配器Adapter是个class template
  • 分配器Allocator是个class template
template 
Algorithm(Iterator itr1, Iterator itr2)
{
  ...
}
template 
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 
void display_category(I itr)
{
  typename iterator_traits::iterator_category cagy;
  _display_category(cagy);
}

使用该打印函数的例子:

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

display_category(array::iterator());
display_category(vector::iterator());
display_category(list::iterator());
display_category(forward::iterator());
display_category(deque::iterator());

各种容器的iterators的iterator_category的typeid

template 
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 
inline iterator_traits::difference_type
__distance(InputIterator first, InputIterator last, input_iterator_tag) {
  iterator_traits::difference_type n = 0;
  while (first != last) {
    ++first; ++n;
  }
  return n;
}
template 
inline iterator_traits {
  return last - first;
}
// ----------------------------------------------------------------------
template 
inline iterator_traits::difference_type
distance(InputIterator first, InputIterator last) {
  typedef typename
    iterator_traits::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 
inline void __advance(InputIterator &i, Distance n, input_iterator_tag) {
  while (n--) ++i;
}
template 
inline void __advance(BidirectionalIterator &i, Distance n, bidirectional_iterator_tag) {
  if (n >= 0) while (n--) ++i;
  else while (n++) --i;
}
template 
inline void __advance(RandomAccessIterator &i, Distance n, random_access_iterator_tag) {
  i += n;
}
// -------------------------------------------------------------------------
template 
inline typename iterator_traits::iterator_category
iterator_category(const Iterator&) {
  typedef typename iterator_traits::iterator_category category;
  return category(); // 此函数协助取出iterator的category, 
                     // 并以此创建一个临时对象.
}

template 
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 或者unarg_function. 这是因为这些仿函数并不是单独存在的,他们可能只是算法的一部分,需要其他算法进行调用,才能发挥作用, 但是如果是的自己可以被其他函数调用,就需要告知调用者 自己的返回值,参数等特性. 这一点跟容器的traits非常类似,把需要告知算法的信息进行统一的封装.

template 
struct unarg_function{
    typedef    Arg    argument_type;
    typedef    Result    result_type;
};

template 
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.

STL与泛型编程 week 4 (Boolan)_第1张图片
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.

你可能感兴趣的:(STL与泛型编程 week 4 (Boolan))