实验3

实验任务1

button.hpp

#pragma once

#include <iostream>
#include <string>

class Button {
public:
   Button(const std::string &label);
   const std::string& get_label() const;
   void click();

private:
   std::string label_;
};

inline Button::Button(const std::string &label): label_{label} {
}

inline const std::string& Button::get_label() const {
   return label_;
}

inline void Button::click() {
   std::cout << "Button '" << label_ << "' clicked\n";
}

window.hpp

#pragma once

#include "button.hpp"

#include <iostream>
#include <vector>
#include <algorithm>

// 窗口类
class Window{
public:
   Window(const std::string &title);
   void display() const;
   void close();
   void add_button(const std::string &label);
   void click_button(const std::string &label);

private:
   bool has_button(const std::string &label) const;

   std::string title_;
   std::vector<Button> buttons_;
};

inline Window::Window(const std::string &title): title_{title} {
   buttons_.push_back(Button("close"));
}

inline void Window::display() const {
   std::string s(40, '*');
   std::cout << s << std::endl;
   std::cout << "window : " << title_ << std::endl;
   int cnt = 0;
   for(const auto &button: buttons_)
       std::cout << ++cnt << ". " << button.get_label() << std::endl;
   std::cout << s << std::endl;
}

inline void Window::close() {
   std::cout << "close window '" << title_ << "'" << std::endl;
   click_button("close");
}

inline bool Window::has_button(const std::string &label) const {
   for(const auto &button: buttons_)
       if(button.get_label() == label)
           return true;
   
   return false;
}

inline void Window::add_button(const std::string &label) {
   if(has_button(label))
       std::cout << "button " << label << " already exists!\n";
   else
       buttons_.push_back(Button(label));
}

inline void Window::click_button(const std::string &label) {
   for(auto &button:buttons_)
       if(button.get_label() == label) {
           button.click();
           return;
       }
           
   std::cout << "no button: " << label << std::endl;
}

task1.cpp

#include "window.hpp"
#include <iostream>

void test(){
   Window w("Demo");
   w.add_button("add");
   w.add_button("remove");
   w.add_button("modify");
   w.add_button("add");
   w.display();
   w.close();
}

int main() {
   std::cout << "用组合类模拟简单GUI:\n";
   test();

   return 0;
}

运行结果

image

  • 问题1:这个范例中,Window 和 Button 是组合关系吗?结合成员 buttons_ 的声明方式(值还是指针)和对象生命周期的管理方式来回答。

是组合关系。声明方式:buttons_元素存放的是Button实体,不是指针或引用。生命周期:按钮随Window创建而产生,window析构时buttons_作为成员先被析构,其中的Button全部销毁,二者同生共死。

  • 问题2:bool has_button(const std::string &label) const; 被设计为私有。① 若将其改为公有接口,有何优点或风险?② 设计类时,如何决策一个成员函数应为 public 还是 private?

优点:外部可以直接查询窗口里是否已有某个按钮。缺点:外部一旦能自由判断,就容易被引导去绕过 add_button 直接操作数据,破坏类自己维护的不变量
决策:第一标准是“用户是否需要”:只有调用者确实需要、并且它属于这个类对外提供的能力时才设为 public;如果只是类内部某个功能执行过程中的辅助步骤,就是实现细节,应当 private。第二层看“会不会破坏对象状态”:只读查询不会破坏状态,风险主要在锁死内部结构;会写状态的更应私有,通过受控的公有函数间接完成,保证检查逻辑总被执行。

  • 问题3:Button 的接口返回 conststd::string&,对比“返回值”两种接口设计在性能和安全性方面的差异。

接口1返回内部成员的 const 引用,不做拷贝,只传一个地址,时间复杂度 O(1)。对 label 这种可能较长、又会被频繁读取的成员优势明显.。const 修饰保证调用者无法通过返回值修改 label_,封装没有被破坏。

  • 问题4:① 把 push_back(Button(xxx)) 改成 emplace_back(xxx),程序是否正常,两种写法有何差别?

程序正常运行,输出与原来逐行一致。差别在于对象构造的次数:push_back(Button("add")) 先在外部构造一个临时 Button,再把它移动构造到 vector 的元素位置上,多了一次临时对象的构造与析构;emplace_back("add") 把实参完美转发到 vector 已分配好的内存里,直接原地构造,省掉临时对象和那次移动。需要注意的是 emplace_back 不做隐式类型转换,实参必须能直接匹配某个构造函数,构造函数为 explicit 或实参能同时匹配多个构造函数时,容易编译不过或产生歧义;本例参数是 std::string,字符串字面量可隐式转换,两种写法等价。

  • ② 用 any_of 改写 has_button 是否可以?③ 用 find_if 改写 click_button 是否可以?
inline bool Window::has_button(const std::string &label) const {
// for(const auto &button: buttons_)
// if(button.get_label() == label)
// return true;
// return false;
return std::any_of(buttons_.begin(), buttons_.end(),
[&](const Button &b) { return b.get_label() == label; });
}

可以。std::any_of(first, last, pred) 对区间 [first, last) 中每个元素调用一元谓词 pred,只要有一个返回 true 就立即返回 true(短路,不再看后面的元素),全部为 false 或区间为空时返回 false。参数 first/last 是迭代器区间,pred 是谓词(这里用 lambda 捕获 label 去比较按钮文字);返回值为 bool。用它改写后,循环与“提前 return”交给算法完成,语义与 has_button 完全一致,也不容易写错循环边界。

  • ③ 用 find_if 改写 click_button 是否可以?
inline void Window::click_button(const std::string &label) {
// for(auto &button:buttons_)
// if(button.get_label() == label) {
// button.click();
// return;
// }
// std::cout << "no button: " << label << std::endl;
auto it = std::find_if(buttons_.begin(), buttons_.end(),
[&](const Button &b) { return b.get_label() == label; });
if (it != buttons_.end())
it->click();
else
std::cout << "no button: " << label << std::endl;
}

可以。std::find_if(first, last, pred) 在 [first, last) 中查找第一个使 pred 为 true 的元素,返回指向它的迭代器;找不到时返回 last(这里是 buttons_.end())。返回类型是输入迭代器类型,const 版本则返回 const_iterator。因此必须先判断 it != buttons_.end() 再解引用,否则对 end 解引用是未定义行为。这样一次遍历同时完成“查找 + 定位”,比手写循环加 return 更简洁。

  • 问题5(选):窗口有上百个按钮时,click_button 的线性查找会成为瓶颈吗?改用 std::map 后 display() 的输出会怎样变化,可以接受吗?

会成为瓶颈。click_button 与 has_button 都是 O(n) 线性查找,每次点击都要从头比字符串,n 到上百时单次点击仍不算慢,但按钮多、点击频繁(或 add 时反复判重)时累积开销明显;add_button 每次插入还要先扫一遍判重,整体是 O(n²)。改用 std::map<std::string, Button>,查找降为 O(log n),且 key 天然唯一,判重可直接用 find,不必再单独写 has_button。

实验任务2

task2.cpp

#include <iostream>
#include <vector>

void test1();
void test2();
void output1(const std::vector<int> &v);
void output2(const std::vector<int> &v);
void output3(const std::vector<std::vector<int>> &v);

int main() {
    std::cout << "深复制验证1: 标准库vector<int>\n";
    test1();

    std::cout << "\n深复制验证2: 标准库vector<int>嵌套使用\n";
    test2();

    return 0;
}

void test1() {
    std::vector<int> v1(5, 42);
    const std::vector<int> v2(v1);

    std::cout << "*****拷贝构造后*****\n";
    std::cout << "v1: "; output1(v1);
    std::cout << "v2: "; output1(v2);

    v1[0] = -1;

    std::cout << "*****修改v1[0]后*****\n";
    std::cout << "v1: "; output1(v1);
    std::cout << "v2: "; output1(v2);
}

void test2() {
    std::vector<std::vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}};
    const std::vector<std::vector<int>> v2(v1);

    std::cout << "*****拷贝构造后*****\n";
    std::cout << "v1:\n"; output3(v1);
    std::cout << "v2:\n"; output3(v2);

    v1[0].push_back(-1);

    std::cout << "*****修改v1[0]后*****\n";
    std::cout << "v1:\n"; output3(v1);
    std::cout << "v2:\n"; output3(v2);
}

// 使用索引+循环,遍历输出vector<int>数据项
void output1(const std::vector<int> &v) {
    if(v.size() == 0) {
        std::cout << '\n';
        return;
    }

    std::cout << v[0];
    for(auto i = 1; i < v.size(); ++i)
        std::cout << ", " << v[i];
    std::cout << '\n';
}

// 使用迭代器+循环,遍历输出vector<int>数据项
void output2(const std::vector<int> &v) {
    if(v.size() == 0) {
        std::cout << '\n';
        return;
    }

    auto it = v.begin();
    std::cout << *it;

    for(it = v.begin() + 1; it != v.end(); ++it)
        std::cout << ", " << *it;
    std::cout << '\n';
}

// 使用auto for分行输出vector<vector<int>>数据项
void output3(const std::vector<std::vector<int>> &v) {
    if(v.size() == 0) {
        std::cout << '\n';
        return;
    }

    for(auto &i: v)
        output2(i);
}

运行结果
image

  • 问题1:测试模块1中 std::vector v1(5, 42); 与 const std::vector v2(v1); 分别完成了什么构造?v1、v2 各包含多少个值为 42 的数据项?

第一行是“指定大小 + 初值”的填充构造:申请 5 个 int 的空间,全部填成 42。第二行调用拷贝构造:按 v1 的大小申请同样空间,再逐元素复制。所以 v1 有 5 个 42,v2 也有 5 个 42,两者各占一块独立内存。

  • 问题2:测试模块2中执行 std::vector<std::vector> v1{{1,2,3},{4,5,6,7}}; 与 const std::vector<std::vector> v2(v1); 后,v1.size()、v2.size()、v1[0].size() 分别是多少?

v1.size() = 2(外层两个 vector 元素),v2.size() = 2(拷贝构造,结构一致),v1[0].size() = 3(第一个内层容器是 {1,2,3})。

  • 问题3:把 v1[0] = -1; 写成 v1.at(0) = -1; 能否实现同等效果?两种用法有何区别?

效果相同,都是把第一个元素改成 -1。区别在是否有边界检查:operator[] 只做指针偏移,不检查下标,越界时属于未定义行为——可能读到别的对象、写坏内存,甚至不崩溃却让数据悄悄错掉;at() 会先比较下标范围,越界抛 std::out_of_range 异常,可以被 try/catch 捕获,便于定位问题。代价是 at() 每次多一次比较,性能略低。调试阶段或下标来路不确定时用 at(),确认下标合法、追求性能时用 []。

  • 问题4:测试模块2中执行 v1[0].push_back(-1); 后,① 用 const std::vector &r = v1[0]; 再输出 r[r.size()-1] 能否输出 -1?为什么?

能输出 -1。关键在于 v1 的元素类型是 std::vector,v1[0] 是一个容器对象而不是一个 int,所以 const std::vector &r = v1[0] 绑定的是这个容器本身。push_back(-1) 之后 v1[0] 变为 {1, 2, 3, -1},r.size() = 4,r.size()-1 = 3 正好是最后一个元素的下标,取到的就是 -1。

  • ② 用 const 引用接收返回值在内存使用上有何优势与限制?

用 const 引用接收只是取别名,零拷贝、不产生临时对象,函数内多次读取时尤其划算。限制:一是只读,不能通过 r 修改 v1[0](不能 push_back、不能赋值);二是别名关系,v1 的变化会“透”到 r 上,反过来 v1 若扩容重新分配、或 v1[0] 被重新赋值,r 立即失效;三是生存期依赖 v1,r 不能活得比 v1 更久。

  • 问题5:① 标准库模板类 vector 的复制构造函数实现的是深拷贝还是浅拷贝?

① 是深拷贝。证据来自运行结果:拷贝后修改 v1[0] = -1,v2 仍是 42.

  • ② vector::at() 接口思考:v 是 vector 时 at(0) 返回什么类型,v 是 const vector 时又返回什么?据此推断 at() 是否必须提供带 const 的重载版本?

v 是 vector 时,v.at(0) 返回 int&(可写引用,能赋值修改);v 是 const vector 时返回 const int&(只读引用)。同一个函数名要给出两种返回类型,只能靠参数表之外的 this 的 const 属性来重载,所以 at() 必须提供带 const 修饰的版本。否则:const 对象只能调用 const 成员函数,若只有非 const 版本,const 对象上根本调不通;而若把接口写死成返回 int&,就等于允许通过 const 对象修改内部数据,const 正确性被破坏。

实验任务3

vectorInt.hpp

#pragma once

#include <iostream>
#include <stdexcept>

// 动态int数组对象类
class vectorInt {
public:
    vectorInt();
    vectorInt(int n);
    vectorInt(int n, int value);
    vectorInt(const vectorInt &vi);
    ~vectorInt();

    int size() const;
    int& at(int index);
    const int& at(int index) const;
    vectorInt& assign(const vectorInt &vi);

    int* begin();
    int* end();
    const int* begin() const;
    const int* end() const;

private:
    int n_;         // 当前数据项个数
    int *pdata_;    // 数据区
};

inline vectorInt::vectorInt(): n_{0}, pdata_{nullptr} {
}

inline vectorInt::vectorInt(int n): n_{n}, pdata_{new int[n]} {
}

inline vectorInt::vectorInt(int n, int value): n_{n}, pdata_{new int[n]} {
    for(auto i = 0; i < n_; ++i)
        pdata_[i] = value;
}

inline vectorInt::vectorInt(const vectorInt &vi): n_{vi.n_}, pdata_{new int[n_]} {
    for(auto i = 0; i < n_; ++i)
        pdata_[i] = vi.pdata_[i];
}

inline vectorInt::~vectorInt() {
    delete [] pdata_;
}

inline int vectorInt::size() const {
    return n_;
}

inline const int& vectorInt::at(int index) const {
    if(index < 0 || index >= n_)
        throw std::out_of_range("vectorInt::at: index out of range");

    return pdata_[index];
}

inline int& vectorInt::at(int index) {
    if(index < 0 || index >= n_)
        throw std::out_of_range("vectorInt::at: index out of range");

    return pdata_[index];
}

inline vectorInt& vectorInt::assign(const vectorInt &vi) {
    if(this == &vi)             // 自赋值保护
        return *this;

    int *ptr;
    ptr = new int[vi.n_];       // 先申请新内存并复制
    for(int i = 0; i < vi.n_; ++i)
        ptr[i] = vi.pdata_[i];

    delete[] pdata_;            // 复制成功后再释放旧内存

    n_ = vi.n_;
    pdata_ = ptr;
    return *this;
}

inline int* vectorInt::begin() {
    return pdata_;
}

inline int* vectorInt::end() {
    return pdata_ + n_;
}

inline const int* vectorInt::begin() const {
    return pdata_;
}

inline const int* vectorInt::end() const {
    return pdata_ + n_;
}

task3.cpp

#include "vectorInt.hpp"

#include <iostream>

void test1();
void test2();
void test3();
void output1(const vectorInt &vi);
void output2(const vectorInt &vi);

int main() {
    std::cout << "测试1: 构造、更新\n";
    test1();

    std::cout << "\n测试2: const对象、赋值\n";
    test2();

    std::cout << "\n测试3: 赋值\n";
    test3();

    return 0;
}

void test1() {
    int n;
    std::cout << "Enter n: ";
    std::cin >> n;

    vectorInt x1(n);
    for(auto i = 0; i < n; ++i)
        x1.at(i) = (i + 1) * 10;
    std::cout << "x1: "; output1(x1);

    vectorInt x2(n, 42);
    vectorInt x3(x2);
    x2.at(0) = -1;
    std::cout << "x2: "; output1(x2);
    std::cout << "x3: "; output1(x3);
}

void test2() {
    const vectorInt x(5, 42);
    vectorInt y;

    y.assign(x);

    std::cout << "x: "; output2(x);
    std::cout << "y: "; output2(y);

    y.at(0) = -1;
    std::cout << "x: "; output2(x);
    std::cout << "y: "; output2(y);
}

void test3() {
    vectorInt x(5, 42);
    std::cout << "x: "; output2(x);

    x.assign(x);
    std::cout << "x: "; output2(x);
}

// 使用xx.at()+循环输出vectorInt对象数据项
void output1(const vectorInt &vi) {
    if(vi.size() == 0) {
        std::cout << '\n';
        return;
    }

    std::cout << vi.at(0);
    for(auto i = 1; i < vi.size(); ++i)
        std::cout << ", " << vi.at(i);
    std::cout << '\n';
}

// 使用迭代器+循环输出vectorInt对象数据项
void output2(const vectorInt &vi) {
    if(vi.size() == 0) {
        std::cout << '\n';
        return;
    }

    auto it = vi.begin();
    std::cout << *it;

    for(it = vi.begin() + 1; it != vi.end(); ++it)
        std::cout << ", " << *it;
    std::cout << '\n';
}

运行结果
image

  • 问题1:把 assign() 改成版本2,运行程序,观察测试3 的输出,逐条指出隐患。
    版本2 的 assign 实现
inline vectorInt& vectorInt::assign(const vectorInt &vi) {
    delete[] pdata_;

    n_ = vi.n_;
    pdata_ = new int[n_];
    for(auto i = 0; i < n_; ++i)
        pdata_[i] = vi.pdata_[i];

    return *this;
}

image

隐患逐条分析:① 缺少自赋值保护。版本2 没有 if (this == &vi) return *this; 这一句,x.assign(x) 时 vi 就是 *this,先 delete[] pdata_ 已经把数据释放,随后的 for 循环却仍从 vi.pdata_ 读数据——这是典型的“先释放、后使用”(use-after-free)。由于紧接着 new int[n_] 很可能复用同一块堆空间,读到的不是崩溃而是未初始化垃圾,更隐蔽:程序不报错,数据却已经错了。② 释放顺序错误,异常不安全。按“先 delete 旧内存、再 new 新内存”的顺序,一旦 new 抛 std::bad_alloc,pdata_ 已是悬垂指针,对象处于非法状态,析构时再 delete[] 就是对已释放内存的二次释放(double free),属未定义行为。③ 中断后状态不可恢复。即使不抛异常,只要拷贝过程中出现任何失败,对象既没有旧数据也没有新数据,违背“赋值失败保持原状”的基本要求。④ 与安全版本的差异代码只有三行的顺序:安全版本先 new 到临时指针 ptr、复制、成功后才 delete 旧内存并更新 n_ 与 pdata_,并且开头有自赋值判断。这三点正是“异常安全 + 自赋值安全”的最小成本。

  • 问题2:非 const 版本 at() 用 static_cast 与 const_cast 转调 const 版本,①static_cast<const vectorInt*>(this) 的作用?转换前后 this 的类型?
inline int& vectorInt::at(int index) {
return const_cast<int&>(
static_cast<const vectorInt*>(this)->at(index)
);
}

非 const 成员函数里的 this 类型是 vectorInt(指向非常量对象)。static_cast<const vectorInt>(this) 给它加上底层 const,得到 const vectorInt*。

  • ② const_cast<int&> 的作用?转换前后的返回类型?

const 版 at() 返回 const int&,而非 const 版要返回可写的 int&,所以用 const_cast<int&> 去掉引用上的 const。转换前是 const int&,转换后是 int&.

  • 问题3: vectorInt 类封装了 begin() 和 end() 的const/非const接口。
    ① 以下代码片段,分析编译器如何选择重载版本,并总结这两种重载分别适配什么使用场景
vectorInt v1(5);
const vectorInt v2(5);
auto it1 = v1.begin(); // 调用哪个版本?
auto it2 = v2.begin(); // 调用哪个版本?

it1 调用非 const 版本,返回 int;it2 调用 const 版本,返回 const int。编译器按“调用对象的 const 属性”选择:v2 是 const 对象,它的 this 是 const vectorInt*,只能匹配 const 成员函数,否则就允许通过常量对象修改内部数据;v1 是非常量对象,两个版本都能匹配,重载决议优先选参数表与 cv 限定完全吻合的非 const 版本。适用场景:非 const 版本用于需要修改元素的场合,const 版本用于只读场合.

  • 构造函数 vectorInt(int n, int value) 、 vectorInt(const vectorInt &vi) 及接口 assign 包含内存块的赋值或复制操作。使用算法 改成如下写法是否可以?回答这3行更新代码的功能。
inline vectorInt::vectorInt(int n, int value): n_{n}, pdata_{new int[n]} {
    std::fill_n(pdata_, n_, value);                        // 更新1
}

inline vectorInt::vectorInt(const vectorInt &vi): n_{vi.n_}, pdata_{new int[n_]} {
    std::copy_n(vi.pdata_, vi.n_, pdata_);                 // 更新2
}

inline vectorInt& vectorInt::assign(const vectorInt &vi) {
    if(this == &vi)
        return *this;

    int *ptr = new int[vi.n_];
    std::copy_n(vi.pdata_, vi.n_, ptr);                     // 更新3
    delete[] pdata_;
    n_ = vi.n_;
    pdata_ = ptr;
    return *this;
}

三处改写都可以,功能与原循环完全等价.std::fill_n(first, count, value) 从 first 开始连续把 count 个位置填成 value,替代“循环逐个赋值”;std::copy_n(first, count, result) 从源首地址起读 count 个元素,连续写到 result 指向的目标区,替代“循环逐个复制”。需要注意算法库的约定是“目标区间必须已有足够空间、算法自身不做边界检查”,这里 new int[n_] 已按 n_ 分配好,满足前提。改写的好处是代码更短、下标与边界不容易写错.

实验任务4

  1. matrix.h
#pragma once

// 类Matrix声明
class Matrix {
public:
    Matrix(int n_rows, int n_cols, double value = 0);   // 构造n_rows*n_cols矩阵对象,初值value
    Matrix(int n_rows, double value = 0);              // 构造n_rows*n_rows方阵对象,初值value
    Matrix(const Matrix &x);                           // 拷贝构造(深拷贝)
    ~Matrix();

    void set(const double *pvalue, int size);          // 按行拷贝pvalue指向的数据,要求size==rows*cols
    void clear();                                      // 矩阵对象数据项置0

    const double& at(int i, int j) const;              // 返回矩阵对象索引(i,j)对应数据项const引用
    double& at(int i, int j);                          // 返回矩阵对象索引(i,j)对应数据项引用

    int rows() const;                                  // 返回矩阵对象行数
    int cols() const;                                  // 返回矩阵对象列数
    void print() const;                                // 按行打印数据

private:
    int n_rows_;         // 矩阵对象内元素行数
    int n_cols_;         // 矩阵对象内元素列数
    double *pdata_;      // 数据区
};

  1. matrix.cpp
#include "matrix.h"

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <stdexcept>

Matrix::Matrix(int n_rows, int n_cols, double value)
    : n_rows_{n_rows}, n_cols_{n_cols}, pdata_{new double[n_rows*n_cols]} {
    std::fill_n(pdata_, n_rows*n_cols, value);
}

Matrix::Matrix(int n_rows, double value): Matrix(n_rows, n_rows, value) {
}

// 拷贝构造(深拷贝):为新对象单独申请一块同样大小的连续内存,再逐项复制
Matrix::Matrix(const Matrix &x)
    : n_rows_{x.n_rows_}, n_cols_{x.n_cols_}, pdata_{new double[x.n_rows_ * x.n_cols_]} {
    std::copy_n(x.pdata_, x.n_rows_ * x.n_cols_, pdata_);
}

// 释放指针指向的内存资源
Matrix::~Matrix() {
    delete[] pdata_;
}

void Matrix::set(const double *pvalue, int size) {
    if(pvalue == nullptr)
        throw std::invalid_argument("pvalue must not be null");
    if(size != n_rows_ * n_cols_)
        throw std::invalid_argument("size must match");

    std::copy_n(pvalue, size, pdata_);
}

void Matrix::clear() {
    std::fill_n(pdata_, n_rows_ * n_cols_, 0);
}

const double& Matrix::at(int i, int j) const {
    if(i < 0 || i >= n_rows_ || j < 0 || j >= n_cols_)
        throw std::out_of_range("i must be [0, n_rows_ - 1] and j must be [0, n_cols_ - 1]");

    return pdata_[i * n_cols_ + j];
}

// 返回矩阵对象索引(i,j)对应的数据项引用(越界则抛出异常)
// 复用 const 版本消除重复:static_cast 加 const -> 取只读引用 -> const_cast 去掉 const
double& Matrix::at(int i, int j) {
    return const_cast<double&>(
        static_cast<const Matrix*>(this)->at(i, j)
    );
}

int Matrix::rows() const {
    return n_rows_;
}

int Matrix::cols() const {
    return n_cols_;
}

// 按行打印数据
void Matrix::print() const {
    for(int i = 0; i < n_rows_; ++i) {
        std::cout << pdata_[i * n_cols_ + 0];
        for(int j = 1; j < n_cols_; ++j)
            std::cout << ", " << pdata_[i * n_cols_ + j];
        std::cout << '\n';
    }
}

  1. task4.cpp
#include <cstdlib>
#include <iostream>
#include <stdexcept>

#include "matrix.h"

void test1();
void test2();
void output(const Matrix &m, int row_index);

int main() {
    std::cout << "测试1: \n";
    test1();

    std::cout << "\n测试2: \n";
    test2();

    return 0;
}

void test1() {
    double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int n, m;
    std::cout << "Enter n and m: ";
    std::cin >> n >> m;

    Matrix m1(n, m);    // 创建矩阵对象m1, 大小n×m
    m1.set(x, n*m);     // 用一维数组x的值按行为矩阵m1赋值

    Matrix m2(m, n);    // 创建矩阵对象m2, 大小m×n
    m2.set(x, m*n);     // 用一维数组x的值按行为矩阵m2赋值

    Matrix m3(n);       // 创建一个n×n方阵对象
    m3.set(x, n*n);     // 用一维数组x的值按行为矩阵m3赋值

    std::cout << "矩阵m1: \n";   m1.print();
    std::cout << "矩阵m2: \n";   m2.print();
    std::cout << "矩阵m3: \n";   m3.print();
}

void test2() {
    Matrix m1(2, 5, -1);
    const Matrix m2(m1);

    std::cout << "矩阵m1: \n";   m1.print();
    std::cout << "矩阵m2: \n";   m2.print();

    m1.clear();
    m1.at(0, 0) = 1;
    m1.at(0, 1) = 2;

    std::cout << "m1更新后: \n";
    std::cout << "矩阵m1第0行 "; output(m1, 0);
    std::cout << "矩阵m2第0行: "; output(m2, 0);
}

// 输出矩阵对象row_index行所有元素
void output(const Matrix &m, int row_index) {
    if(row_index < 0 || row_index >= m.rows())
        throw std::out_of_range("row_index must in [0, m.rows()-1]");

    std::cout << m.at(row_index, 0);
    for(int j = 1; j < m.cols(); ++j)
        std::cout << ", " << m.at(row_index, j);
    std::cout << '\n';
}

image

  • 回答问题:接口 void set(const double *pvalue, int size); 的设计与测试模块,是否暴露出潜在风险?(提示:当测试模块中数组x做如下改动,仍然测试截图运行输入2 3或2 5,结果会暴露什么问题)如何优化 set() 接口,确保该接口使用时更安全、可靠。

存在风险。set 只能校验 size == rowscols 这一个条件,无法知道 pvalue 实际指向的数组有多长——裸指针不携带长度信息,类只能信任调用者。优化方向:① 在 set 里补上 size 的合法性校验,size <= 0 或与 rowscols 不符时抛异常;构造时同样校验 n_rows、n_cols 为正,否则抛出异常,避免 new double[0] 之类的问题。

实验任务5

contact.hpp

#pragma once

#include <iostream>
#include <string>

// 联系人类
class Contact {
public:
    Contact(const std::string &name, const std::string &phone);

    const std::string &get_name() const;
    const std::string &get_phone() const;
    void display() const;

private:
    std::string name_;    // 必填项
    std::string phone_;   // 必填项
};

inline Contact::Contact(const std::string &name, const std::string &phone):name_{name},
phone_{phone} {
}

inline const std::string& Contact::get_name() const {
    return name_;
}

inline const std::string& Contact::get_phone() const {
    return phone_;
}

inline void Contact::display() const {
    std::cout << name_ << ", " << phone_;
}

contactbook.hpp

# pragma once

#include "contact.hpp"

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

// 通讯录类
class ContactBook {
public:
    void add(const std::string &name, const std::string &phone);  // 添加联系人
    void remove(const std::string &name);                         // 移除联系人
    void find(const std::string &name) const;                     // 查找联系人
    void display() const;                                         // 显示所有联系人
    size_t size() const;

private:
    int index(const std::string &name) const;   // 返回联系人在vector内索引,如不存在,返回-1
    void sort();                                // 按姓名字典序升序排序通讯录

private:
    std::vector<Contact> contacts_;
};

inline void ContactBook::add(const std::string &name, const std::string &phone) {
    if(index(name) == -1) {
        contacts_.push_back(Contact(name, phone));
        std::cout << name << " add successfully.\n";
        sort();
        return;
    }

    std::cout << name << " already exists. fail to add!\n";
}

inline void ContactBook::remove(const std::string &name) {
    int i = index(name);

    if(i == -1) {
        std::cout << name << " not found, fail to remove!\n";
        return;
    }

    contacts_.erase(contacts_.begin()+i);
    std::cout << name << " remove successfully.\n";
}

inline void ContactBook::find(const std::string &name) const {
    int i = index(name);

    if(i == -1) {
        std::cout << name << " not found!\n";
        return;
    }

    contacts_[i].display();
    std::cout << '\n';
}

inline void ContactBook::display() const {
    for(auto &c: contacts_) {
        c.display();
        std::cout << '\n';
    }
}

inline size_t ContactBook::size() const {
    return contacts_.size();
}

// 待补1: int index(const std::string &name) const;实现
// 返回联系人在contacts内索引;如不存在,返回-1
inline int ContactBook::index(const std::string &name) const {
    for(size_t i = 0; i < contacts_.size(); ++i) {
        if(contacts_[i].get_name() == name)
            return static_cast<int>(i);
    }

    return -1;
}

// 待补2: void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录
inline void ContactBook::sort() {
    std::sort(contacts_.begin(), contacts_.end(),
              [](const Contact &a, const Contact &b) {
                  return a.get_name() < b.get_name();
              });
}

task5.cpp

#include "contactbook.hpp"

void test() {
    ContactBook contactbook;

    std::cout << "1. add contacts\n";
    contactbook.add("Bob", "18199357253");
    contactbook.add("Alice", "17300886371");
    contactbook.add("Linda", "18184538072");
    contactbook.add("Alice", "17300886371");

    std::cout << "\n2. display contacts\n";
    std::cout << "There are " << contactbook.size() << " contacts.\n";
    contactbook.display();

    std::cout << "\n3. find contacts\n";
    contactbook.find("Bob");
    contactbook.find("David");

    std::cout << "\n4. remove contact\n";
    contactbook.remove("Bob");
    contactbook.remove("David");

    std::cout << "\n5. display contacts\n";
    std::cout << "There are " << contactbook.size() << " contacts.\n";
    contactbook.display();
}

int main() {
    test();
}

index() 用下标循环遍历 contacts_,逐个比较 get_name(),找到返回下标(size_t 转 int,容器规模远小于 int 上限),找不到返回 -1,正好与 remove() 中 erase(begin()+i) 的用法衔接。sort() 用 std::sort 加 lambda 比较器按姓名升序排列,每次 add 成功后调用,保证 display() 的输出始终是字典序;由于 add 先判重再插入,排序不会打乱“不重复”这个不变量。两个函数都保持 private,只在类内部被 add/remove/find 调用。

拓展思考(选):要让这个通讯录更接近手机通讯录,可在不动现有接口的前提下逐步扩展——新增 update(name, newPhone) 修改号码,内部复用 index() 定位;add 时校验手机号格式(11 位数字)与姓名非空,非法输入直接提示失败;把 contacts_ 持久化到文本/CSV 文件,构造时读入、析构或显式 save() 时写回;检索支持按姓名子串的模糊匹配(此时用 std::string::find 判断包含关系),进一步可加分组字段并用 std::map<std::string, std::vector> 管理。扩展的原则是:只新增公有接口、不改动 add/remove/find/display 的签名与输出格式,内部即使把 vector 换成 map 也保持对外行为不变,这样既兼容既有调用代码,也便于维护。

posted @ 2026-11-26 23:08  Zzx07  阅读(6)  评论(0)    收藏  举报