20200219

@ShiKaiWi

Plan

60min: CPP Algorithm Based on Template

Notes

总结:算法可以应用在使用迭代器封装的容器上面。

+-----------+     
| Algorithm |     
+-----------+     
      |           
      |   apply   
      |           
      v           
+-----------+     
|  Iterator |     
|+----------+     
||Container |     
++----------+     

收获点:

  • lambada 可以采用各种各样的捕获方式,其返回值的推断能力有限(只能在有且只有一个 return 语句的时候进行成功推断,否则推断结果一律为 void)。
  • bind 可以将一个 function pointer 转换为一个 callable object,并且支持 capture,捕获引用需要使用 ref/cref 函数。
  • 存在 crbegin 这样的反向迭代器。
  • 迭代器分为五大类:输入、输出、前向、双向、随机访问。

练习代码:

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <numeric>

using namespace std::placeholders;

void test_equal() {
  std::list<std::string> roster1 = {"1", "2", "3", "4"};
  std::list<std::string> roster2 = {"1", "2", "3"};
  auto equals = equal(roster1.cbegin(), roster1.cend(), roster2.cbegin());
  std::cout << "equals result: " << equals << std::endl;
}

void test_for_each_output(std::ostream &os = std::cout, char end_char = ';') {
  std::list<std::string> words = {"1", "2", "3", "4"};
  for_each(words.cbegin(), words.cend(),
           [&, end_char](const std::string &s) { os << s << end_char; });
}

void print_for_binding(std::ostream &os, const std::string s, char end_char) {
  os << s << end_char;
}

void test_for_each_by_binding() {
  std::list<std::string> words = {"b1", "b2", "b3", "b4"};
  for_each(words.cbegin(), words.cend(),
           bind(print_for_binding, ref(std::cout), _1, ';'));
}

void test_stream_iterator() {
  std::istream_iterator<int> in(std::cin), eof;
  std::cout << accumulate(in, eof, 0) << std::endl;
}

void print_numbers_by_ostream_iterator() {
  std::list<std::string> words = {"p1", "p2", "p3", "p4"};
  std::ostream_iterator<std::string> out(std::cout, ",");
  copy(words.cbegin(), words.cend(), out);
  std::cout << std::endl;
}

int main() {
  test_equal();
  test_for_each_output();
  test_for_each_by_binding();
  // test_stream_iterator();
  print_numbers_by_ostream_iterator();
  return 1;
}

More