open-courses
  • 公开课笔记
  • CMU 15-445/645 Database Systems
    • Relational Data Model
    • Advanced SQL
    • Database Storage
    • Buffer Pools
    • Hash Tables
    • Tree Indexes
    • Index Concurrency Control
    • Query Processing
    • Sorting&Aggregations
    • Join Algorithms
    • Query Optimization
    • Parallel Execution
    • Embedded Database Logic
    • Concurrency Control Theory
    • Two Phase Locking
    • Timestamp Ordering Concurrency Control
    • Multi-Version Concurrency Control
    • Logging Schemes
    • Database Recovery
    • Introduction to Distributed Databases
    • Distributed OLTP Databases
    • Distributed OLAP Databases
  • UCB - CS162
    • OS intro
    • Introduction to the Process
    • Processes, Fork, I/O, Files
    • I/O Continued, Sockets, Networking
    • Concurrency: Processes & Threads
    • Cooperating Threads, Synchronization
    • Semaphores, Condition Variables, Readers/Writers
    • Scheduling
    • Resource Contention & Deadlock
    • Address Translation, Caching
    • File System (18,19,20)
    • Distributed Systems, Networking, TCP/IP, RPC (21,22)
    • Distributed Storage, Key-Value Stores, Security (23)
    • Security & Cloud Computing (24)
    • Topic: Ensuring Data Reaches Disk
  • MIT - 6.006
    • Sequence and Set Interface
    • Data Structure for Dynamic Sequence Interface
    • Computation Complexity
    • Algorithms and Computation
    • Structure Of Computation
    • Graph & Search
    • Tree & Search
    • Weighted Shortest Paths
    • String Matching, Karp-Rabin
    • Priority Queue Interface & Implementation
    • Dictionary Problem & Implementation
    • Sorting
    • Dynamic Programming
    • Backtracking
    • Self-Balancing Tree
  • MIT - 6.824
    • 2PC & 3PC
    • Introduction and MapReduce
    • RPC and Threads
    • Primary/Backup Replication
    • Lab: Primary/Backup Key/Value Service
    • Google File System (GFS)
    • Raft
    • Lab: Raft - Leader Election
    • Lab: Raft - Log Replication
  • Stanford-CS107
    • 原始数据类型及相互转化
    • 指鹿为马
    • 泛型函数
    • 泛型栈
    • 运行时内存结构
    • 从 C 到汇编
    • 函数的活动记录
    • C 与 C++ 代码生成
    • 编译的预处理过程
    • 编译的链接过程
    • 函数的活动记录续、并发
    • 从顺序到并发和并行
    • 信号量与多线程 1
    • 信号量与多线程 2
    • 复杂多线程问题
    • 函数式编程 - Scheme 1
    • 函数式编程 - Scheme 2
    • 函数式编程 - Scheme 3
    • 函数式编程 - Scheme 4
    • 函数式编程 - Scheme 5
    • Python 基础
  • MIT - 6.001 - SICP
    • 什么是程序
    • 程序抽象
    • 替代模型
    • 时间/空间复杂度
    • 数据抽象
    • 高阶函数
    • Symbol
    • 数据驱动编程与防御式编程
    • 数据抽象中的效率与可读性
    • 数据修改
    • 环境模型
    • 面向对象-消息传递
    • 面向对象 - Scheme 实现
    • 构建 Scheme 解释器
    • Eval-Apply Loop
    • Normal Order (Lazy) Evaluation
    • 通用机
    • 寄存器机器
    • 子程序、栈与递归
    • 在寄存器机器中执行
    • 内存管理
  • MIT - 6.046
    • Randomized Algorithms
    • Skip Lists
  • System Design
    • Twitter
    • Cache Consistency & Coherence
  • DDIA 笔记
    • Replication
    • Transactions
    • The Trouble with Distributed Systems
    • Consistency & Consensus
  • Papers We Love
    • Consistent Hashing and Random Trees (1997)
    • Dynamic Hash Tables (1988)
    • LFU Implementation With O(1) Complexity (2010)
    • Time, Clocks, and the Ordering of Events in a Distributed System (1978)
    • Dapper, a Large-Scale Distributed Systems Tracing Infrastructure (2010)
    • Gorilla: A Fast, Scalable, In-Memory Time Series Database (2015)
  • Release It 笔记
    • Anti-patterns & Patterns in Microservice Architecture
  • Database Design
    • Log Structured Merge (LSM) Tree & Usages in KV Stores
    • Prometheus
Powered by GitBook
On this page
  1. Stanford-CS107

泛型函数

第四、五课

从 “指鹿为马” 到泛型函数 (Generic Function)

泛型函数指的是一类对所有类型都适用的函数,使得程序员在使用强类型语言时,不需要为每种类型都写一个相同功能的函数,这也是 DRY (Don't Repeat Yourself) 的一种体现。

通过前两课,我们获得了“指鹿为马”的技能 — 通过强制转换告诉编译器,一个指向 A 类型的指针实际上是一个指向 B 的指针。C 语言中有一个特殊的指针 void * — 无类型指针。无类型指针可以指向任何数据,如果我们用它用作函数的参数和返回值,那么这个参数或返回值就可以是任何类型的指针,这也为构造泛型函数提供原料。

例:泛型交换函数 (Generic Swap Function)

#include <string.h>

void swap(void *vp1, void *vp2, int size) {
  char buffer[size];
  memcpy(buffer, vp1, size);
  memcpy(vp1, vp2, size);
  memcpy(vp2, buffer, size);
}

// usage
int main(int argc, char **argv) {
  int a = 1;
  int b = 2;
  swap(&a, &b, sizeof(int));

  double f1 = 0.5;
  double f2 = 0.8;
  swap(&f1, &f2, sizeof(double));

  char *husband = strdup("Fred");
  char *wife = strdup("Wilma");
  swap(&husband, &wife, sizeof(char *)); // 注意这里,交换的是两个指针
}

例:泛型线性搜索 (Generic Linear Search)

void *lsearch(void *key, void *base, int size, int elemSize) {
  for (int i = 0; i < size; i++) {
    void *elemAddr = (char *)base + i * elemSize;
    if (memcmp(key, elemAddr, elemSize) == 0) {
      return elemAddr;
    }
  }
  return NULL;
}

同理,不论是什么类型的数组,只要知道数组所在内存的地址 (base) 和查询目标内存的地址 (key),以及每个元素的长度 (elemSize) — 字节数,就可以拿着目标所在内存段与数组所在内存段进行一一比对,直到找到或者遍历数组结束为止。

更进一步,可以制定比较两个元素的方法

void *lsearch(void *key, void *base,
              int size, int elemSize,
              int (*cmpfn)(void *, void *)) {
  for (int i = 0; i < size; i++) {
    void *elemAddr = (char *)base + i * elemSize;
    if (cmpfn(key, elemAddr) == 0) return elemAddr;
  }
  return NULL;
}

比较 int

int array[] = {4, 2, 3, 7, 11, 6};
int size = sizeof(array) / sizeof(int);
int number = 7;
int IntCmp (void *elem1, void *elem2) {
  int *ip1 = elem1;
  int *ip2 = elem2;
  return *ip1 - *ip2;
}
int *found = lsearch(&number, array, size, sizeof(int), IntCmp);

比较 string

char *notes[] = {"Ab", "F#", "B", "Gb", "D"};
char *favorateNote = "Gb";
int size = sizeof(notes) / sizeof(char *);
int StrCmp(void *vp1, void *vp2) {
  char *s1 = *(char **)vp1;
  char *s2 = *(char **)vp2;
  return strcmp(s1, s2);
}
char **found = lsearch(&favorateNode, notes, size, sizeof(char *), StrCmp);

小结:

本课内容让我联想到软件开发的基本定律 (Fundamental theorem of software engineering):

All problems in computer science can be solved by another level of indirection

参考

Previous指鹿为马Next泛型栈

Last updated 6 years ago

本质上,不论是什么类型的数据,只要这些数据在内存当中是连续的,那么交换它们实际上就是交换两段连续的内存。只要知道两段内存的地址 (vp1, vp2),以及内存长度 (size),就可以使用 generic swap 来实现交换。最后一例中的字符串交换示意图见下图:

Stanford CS107: lecture 4
Stanford CS107: lecture 5
Github: ZhengHe-MD - lecture codes