CS106B学习笔记 (lecture 02&03)

这篇博客详细介绍了CS106B课程中关于C++的function声明、默认参数、值与引用语义,以及Lecture 03中重点讲解的Vector(动态数组)和Grid的数据结构。Vector提供了方便的插入和删除操作,而Grid则是一种强大的二维数组,支持多种遍历方式。当传递Grid作为参数时,通常建议使用引用以避免复制开销。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CS106B home page

Lecture 02

  • 在main()之前声明function。
  • Default parameters
    参数可以设置默认值。
    带默认值的参数必须放在参数表的最后。
  • Value semantics:In java and C++, when variables (int, double) are passed as parameters, their values are copied.
    -Modifying a parameter will affect the variable passed in.
  • Reference semantics: If you declare a parameter with an & after its type, it will link the functions to the same place in memory.
    -Modifying a parameter will affect the variable passed in. 引用必须是有内存的地址,不能引用值。C++只会传递copy,除非引用
  • Output parameters: (they don’t have to have values, just providing
    space to store the output values.)
  • Procedural decomp.
  • Strings, can be changed.
  • Character

Lecture 03

Vectors (list)

#include "vector.h"

  • vector (aka list): a collection of elements with 0-based indexes
    -like a dynamically-resizing array (Java ArrayList or Python list)
// initialize a vector containing 5 integers
Vector<int> nums {42, 17, -6, 0, 28};

Vector<string> names;
names.add("Stu");      // {"Stu"}
names.add("Marty");  // {"Stu", "Marty"}
names.insert(0, "Ed"); // {"Ed", "Stu", "Marty"}
  • Why not arrays?
    a) Arrays have fixed size and cannot be easily resized. (no .length field)
    b) C++ lets you index out of the array bounds
    c) An array does not support many operations that you’d want: inserting/deleting elements into the front/middleback of the array, reversing, sorting the elements, earching for a given value…
  • Vector insert/remove

v.insert(2, 42); //v[2] = 42
-shift elements right to make room for the new element
v.remove(1)
-shift elements left to cover the space left by the removed element.

Grid

#include "gird.h"
like a 2D array, but more powerful
must specify element type in <> (a template or a type parameter)

//construding a Grid
Grid<int> matrix(3, 4);
matrix[0][0] = 75;
...
//or specify elements in {}
Grid<int> matrix = {
 {75, 61, 83, 71},
 {94, 89, 98, 100},
 {63, 54, 51, 49}
};
Looping over a grid

Row-major order:
1. for loop
2. “for each” loop for (int value : grid)

Column-major order:
1. for loop

Grid as parameter

When a Grid is passed by value, C++ makes a copy of its contents.
-Copying is slow; you should usually pass by reference with &
-If the code won’t modify the grid, also pass it as const

A) int computeSum(const Grid g) {
B) void invert(Grid& matrix) {

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值