实验3

实验任务1

一、代码

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";
}

2. window.hpp

#pragma once
#include "button.hpp"
#include <algorithm>
#include <iostream>
#include <vector>

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;
}

3. 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;
}

二、运行截图

1. 原程序运行

image

重复添加 add 时提示按钮已存在,显示的按钮依次为 close、add、remove、modify;关闭窗口时调用 close 按钮。

2. 标准库改写后运行

image
image

将按钮添加改为 emplace_back,查找改为 any_of 和 find_if 后,原测试模块的输出应保持一致。

三、问题回答

1. Window和Button是组合关系吗?

是。buttons_ 的类型是 std::vector<Button>,容器保存的是按钮对象本身,不是指向外部按钮的裸指针。窗口负责持有这些按钮,窗口销毁时,成员容器会自动销毁其中的按钮,体现了“窗口拥有按钮”的 has-a 关系。

2. has_button改为公有接口有什么优点或风险?如何决定public和private?

① 改为公有后,外部可以在操作前查询按钮是否存在。它是只读查询,不会直接破坏窗口状态;代价是增加了需要长期维护的公开接口,外部代码也可能依赖它的查询规则。

② 外部用户确实需要、含义稳定且能维护对象约束的操作,可以设为 public;只供内部协作、属于实现细节的辅助函数,适合设为 private。本例中,添加和点击操作已经会处理“不存在”或“重复”的情况,因此可以把查询函数保留为私有。

3. get_label返回const引用和返回值有什么区别?

返回 const std::string& 不复制字符串,开销小,而且不能通过该引用修改标签;但引用依赖原字符串对象的生命期,按钮销毁或容器重分配导致按钮对象搬迁后,原先保存的引用可能悬空。

返回 std::string 会得到独立副本,调用者可以安全保留或修改副本,不依赖按钮的生命期;代价是复制成员字符串,可能发生额外内存分配。

4. 标准库探索

① 将两处 push_back(Button(...)) 改成 emplace_back(...) 后,程序仍可正常运行,输出内容一致。

// Window构造函数中
buttons_.emplace_back("close");

// add_button的else分支中
buttons_.emplace_back(label);

push_back(Button(label)) 先构造临时按钮,再把它移动或复制到容器中;emplace_back(label) 直接在容器提供的位置构造按钮,可以省去这个临时对象。容器扩容时,两种方式都仍可能搬迁已有元素。

② 可以用 std::any_of() 改写 has_button():

inline bool Window::has_button(const std::string &label) const {
    return std::any_of(buttons_.begin(), buttons_.end(),
        [&](const Button &b) { return b.get_label() == label; });
}

前两个参数指定半开区间 [begin, end),第三个参数是判断条件。只要有一个按钮满足条件,就返回 true;全部不满足或区间为空时返回 false。

③ 可以用 std::find_if() 改写 click_button():

inline void Window::click_button(const std::string &label) {
    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;
}

前两个参数指定查找范围,第三个参数是判断条件。它返回第一个满足条件的元素的迭代器;找不到时返回 end(),此时不能解引用。

5. 按钮增多时,是否应该换成map?(选答)

线性查找的时间复杂度是 O(n),但上百个按钮通常还不足以单独构成瓶颈,要结合查找频率和实际测量判断。按标签组织的 std::map 查找复杂度为 O(log n),但有结点分配、指针访问等开销。

当前 vector 按添加顺序显示:close、add、remove、modify。若改用以标签为键的默认 map 并直接遍历,会按键的字典序显示:add、close、modify、remove。如果按钮顺序代表界面布局,这种变化就不能直接接受;若需求本来就是按名称排序,则可以接受。

实验任务2

一、代码

1. 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);
}

void output1(const std::vector<int> &v) {
    if (v.empty()) {
        std::cout << '\n';
        return;
    }
    std::cout << v[0];
    for (std::size_t i = 1; i < v.size(); ++i)
        std::cout << ", " << v[i];
    std::cout << '\n';
}

void output2(const std::vector<int> &v) {
    if (v.empty()) {
        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';
}

void output3(const std::vector<std::vector<int>> &v) {
    if (v.empty()) {
        std::cout << '\n';
        return;
    }
    for (const auto &row: v)
        output2(row);
}

二、运行截图

(此处插入“03_实验任务2_vector深拷贝.png”)

一维测试中,修改 v1[0] 后,v2 仍是5个42;嵌套测试中,只有 v1 的第一行增加 -1,v2 保持原状。

三、问题回答

1. v1和v2分别进行了什么构造?各有多少个42?

std::vector<int> v1(5, 42); 使用“数量+初值”的构造函数,创建5个值为42的整数。

const std::vector<int> v2(v1); 调用复制构造函数,复制 v1,并把 v2 定义为常对象。因此刚构造完成时,二者各有5个42。

2. 嵌套vector的size分别是多少?

刚执行完两行构造语句时,v1.size() 为2,v2.size() 为2,v1[0].size() 为3。外层有两行,第一行有3个整数,第二行有4个整数。

3. v1[0]与v1.at(0)有什么区别?

本例索引0有效,二者赋值效果相同。operator[] 不进行标准要求的越界异常检查,索引越界会产生未定义行为;at() 会检查范围,越界时抛出 std::out_of_range,便于发现错误。

4. const引用r能否输出新增的-1?有什么优势和限制?

可以。执行 v1[0].push_back(-1) 后,再把 r 绑定到第一行:

const std::vector<int> &r = v1[0];
std::cout << r[r.size() - 1] << std::endl;

r 就是对该行的只读引用,最后一个元素是 -1。引用不会复制整行数据,节省内存和复制开销;但不能通过 r 修改该行,也不能在原行对象销毁或因外层容器重分配而失效后继续使用。

5. vector是深拷贝还是浅拷贝?at为什么需要const重载?

① 本例中的 vector<int> 复制后有独立的元素存储,修改 v1 不影响 v2。嵌套的 vector<vector<int>> 会复制各个内层容器,修改原第一行也不影响副本,体现了深拷贝。

但这不等于任何元素类型都递归复制其外部资源。例如 vector<int*> 复制的是指针值,不会自动复制指针指向的整数。

② 对普通 vector<int>,at(0) 返回 int&,允许修改元素;对 const vector<int>,返回 const int&,只允许读取。为了同时支持两种对象并保持常量约束,标准库提供了对应的两个重载。

实验任务3

一、代码

1. vectorInt.hpp

#pragma once
#include <stdexcept>

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 (int i = 0; i < n_; ++i)
        pdata_[i] = value;
}

inline vectorInt::vectorInt(const vectorInt &vi)
    : n_{vi.n_}, pdata_{new int[n_]} {
    for (int 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 = 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 n_ == 0 ? pdata_ : pdata_ + n_;
}

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

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

2. 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 (int 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);
}

void output1(const vectorInt &vi) {
    if (vi.size() == 0) {
        std::cout << '\n';
        return;
    }
    std::cout << vi.at(0);
    for (int i = 1; i < vi.size(); ++i)
        std::cout << ", " << vi.at(i);
    std::cout << '\n';
}

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';
}

二、运行截图

1. 安全版本

image

输入 n = 6。x1 为 10、20、30、40、50、60;修改 x2 不影响 x3,修改 y 不影响 x。执行 x.assign(x) 前后都应保持5个42。

2. assign版本2

image

同样输入6。本次 Dev-C++ 运行中,test3() 自赋值前为5个42,自赋值后出现了不同的异常整数,原数据未能保留。该版本存在未定义行为,截图仅反映本次运行,不能作为固定预期值。

三、问题回答

1. assign版本2有什么安全隐患?

版本2如下,验证时只替换这一段,验证后恢复上面的安全版本:

inline vectorInt& vectorInt::assign(const vectorInt &vi) {
    delete[] pdata_;
    n_ = vi.n_;
    pdata_ = new int[n_];
    for (int i = 0; i < n_; ++i)
        pdata_[i] = vi.pdata_[i];
    return *this;
}

① 没有处理自赋值。执行 x.assign(x) 时,vi 与当前对象是同一个对象,第一步就释放了原来的5个42。重新分配后,vi.pdata_ 也指向新数组,循环实际变成读取尚未初始化的新元素再写回自身,原数据已经丢失。

② 自赋值时会读取未初始化的 int,产生未定义行为。结果可能是0、看似随机的数据,也可能碰巧像原值,不能依靠某一次输出判断代码安全。

③ 先删除旧内存,再申请新内存,异常安全性差。如果 new 抛出异常,旧数据已经丢失,pdata_ 还可能保留悬空地址,后续析构存在重复释放风险,n_ 与有效存储也不再匹配。

安全版本先判断自赋值,再“申请新内存 → 复制数据 → 释放旧内存 → 更新成员”。对于本例的整数复制,如果申请失败,原对象仍保持原状。

2. at中的static_cast和const_cast分别有什么作用?

非 const 版本可以改写为:

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 vectorInt*,不改变对象地址,目的是调用 const 版本的 at(),复用其中的越界检查。

② const 版本返回 const int&,外层 const_cast<int&> 将其转换为 int&,让普通对象的元素仍然可以修改。这里实际调用者是非 const 对象,因此可以恢复可写访问;不能据此任意修改真正的常量对象。

3. begin和end如何选择重载?原始指针为什么也能作为迭代器?

vectorInt v1(5);
const vectorInt v2(5);
auto it1 = v1.begin();
auto it2 = v2.begin();

① v1 是普通对象,优先调用非 const 版本,it1 为 int*,可以读写所指元素。v2 是常对象,只能调用 const 版本,it2 为 const int*,只能读取所指元素。end() 的重载选择规则相同。

② 迭代器首先是一组操作和语义约定,不一定非得是包装指针的类。对于连续数组,原始指针本身支持解引用、递增、比较、随机访问,可以充当迭代器。end() 表示尾后位置,可用于比较,不能解引用。链表等容器的迭代器还需要封装结点跳转,不能简单等同于连续内存指针。

4. 能否用fill_n和copy_n替换循环?

可以,加入 #include <algorithm> 后,分别替换对应循环即可:

// 更新1:将pdata_开始的n_个元素赋成value
std::fill_n(pdata_, n_, value);

// 更新2:把vi的n_个元素复制到新对象的数据区
std::copy_n(vi.pdata_, vi.n_, pdata_);

// 更新3:把vi的n_个元素复制到assign临时申请的数据区
std::copy_n(vi.pdata_, vi.n_, ptr);

这些算法表达了填充或复制的意图,但不会替代内存分配、目标容量保证和自赋值判断。assign() 仍应保留安全版本的执行顺序。

实验任务4

一、代码

1. matrix.h

#pragma once

class Matrix {
public:
    Matrix(int n_rows, int n_cols, double value = 0);
    Matrix(int n_rows, double value = 0);
    Matrix(const Matrix &x);
    ~Matrix();

    void set(const double *pvalue, int size);
    void clear();
    const double& at(int i, int j) const;
    double& at(int i, int j);
    int rows() const;
    int cols() const;
    void print() const;

private:
    int n_rows_;
    int n_cols_;
    double *pdata_;
};

2. matrix.cpp

#include "matrix.h"
#include <algorithm>
#include <iostream>
#include <limits>
#include <stdexcept>

Matrix::Matrix(int n_rows, int n_cols, double value)
    : n_rows_{n_rows}, n_cols_{n_cols}, pdata_{nullptr} {
    if (n_rows <= 0 || n_cols <= 0)
        throw std::invalid_argument("rows and cols must be positive");
    if (n_rows > std::numeric_limits<int>::max() / n_cols)
        throw std::length_error("matrix is too large");

    int count = n_rows_ * n_cols_;
    pdata_ = new double[count];
    std::fill_n(pdata_, count, 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_, n_rows_ * n_cols_, pdata_);
}

Matrix::~Matrix() {
    delete[] pdata_;
}

void Matrix::set(const double *pvalue, int size) {
    if (size != n_rows_ * n_cols_)
        throw std::invalid_argument("size must match");
    if (pvalue == nullptr)
        throw std::invalid_argument("source pointer must not be null");
    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("matrix index out of range");
    return pdata_[i * n_cols_ + j];
}

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 << at(i, 0);
        for (int j = 1; j < n_cols_; ++j)
            std::cout << ", " << at(i, j);
        std::cout << '\n';
    }
}

3. 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.set(x, n * m);

    Matrix m2(m, n);
    m2.set(x, m * n);

    Matrix m3(n);
    m3.set(x, n * n);

    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);
}

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';
}

二、运行截图

1. 完整实现运行

image
按要求换用输入 2 5。m1 是2×5,m2 是5×2,m3 是2×2。测试2中,修改 m1 后,它的第0行为 1, 2, 0, 0, 0,复制得到的 m2 第0行仍为5个 -1。

2. 源数组过短验证

image

仅把测试数组改为 double x[5] = {1, 2, 3, 4, 5};,输入仍为 2 5。本次截图中,前5项正常,随后读出了异常的极小浮点数。即使程序返回0,也不能说明访问合法。验证后恢复原来的1000项数组;这项验证本身包含未定义行为。

三、问题回答

1. set接口与测试模块有什么潜在风险?

set(const double *pvalue, int size) 只能检查传入的 size 是否等于矩阵元素总数,无法从裸指针知道源数组的真实长度。即使增加空指针检查,也不能识别“源数组太短但传入size很大”的情况。

如果把测试数组改成:

double x[5] = {1, 2, 3, 4, 5};

输入 2 3 时,m1.set(x, 6) 会尝试读取6项;输入 2 5 时,m1.set(x, 10) 会尝试读取10项。两者都超过数组实际的5项,属于越界读取,产生未定义行为。可能出现异常数值或崩溃,也可能暂时看不出问题,不能把某种输出当作必然结果。

原来的 x[1000] 中,前10项显式初始化,余下元素自动初始化为0,不能把这些合法的0误判为越界垃圾值;但输入维度过大时,它同样可能不够长。

2. 如何让set更安全?

在本次“不得修改或新增接口”的约束下,应检查矩阵维度、大小匹配与空指针,并由调用者保证源区域有效且至少含有 size 项。当前接口无法彻底消除长度被错误填写的风险。

若允许改进接口,可以用 const std::vector<double>&,并在函数内读取真实的 size();接收固定数组时,可以用数组引用模板推导长度。C++20还可以使用 std::span<const double> 传递一段带长度的视图,但调用方构造视图时仍须提供有效范围。

如果保持原接口不变,调用处至少应先依据源数组的真实元素数检查各矩阵需要的数量,再调用 set(),不能直接把矩阵大小当成源数组长度。

本次实现还修正了示例 at() 中的边界判断:i == rows() 或 j == cols() 都已越界,因此必须使用 >=,不能只判断 >。

3. 内部改用vector有什么好处?(选答)

用 std::vector<double> 保存数据,可以继续按 i * n_cols_ + j 访问,底层仍是连续内存;复制、析构和复制赋值等资源管理可交给容器,减少手写内存管理和异常处理代码,这体现了 RAII 和零规则。

在等价的存储和访问方式下,它通常能保留接近裸数组的效率,但不能笼统保证所有场景性能完全一致。只替换内部存储,也不能自动解决 set() 的源指针长度问题。

实验任务5

一、代码

1. 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_;
}

2. 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;
    void sort();
    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();
}

inline int ContactBook::index(const std::string &name) const {
    for (std::size_t i = 0; i < contacts_.size(); ++i)
        if (contacts_[i].get_name() == name)
            return static_cast<int>(i);
    return -1;
}

inline void ContactBook::sort() {
    std::sort(contacts_.begin(), contacts_.end(),
              [](const Contact &a, const Contact &b) {
                  return a.get_name() < b.get_name();
              });
}

3. 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();
}

二、运行截图

image

重复添加 Alice 会失败;首次显示3个联系人,顺序为 Alice、Bob、Linda。查询 Bob 成功,查询 David 失败;删除 Bob 成功,删除 David 失败,最终剩2个联系人。

三、问题回答

1. index和sort是如何实现的?

index() 逐项比较联系人姓名,找到后返回其索引,否则返回 -1。使用字符串的 == 比较,查找区分大小写。

sort() 使用 std::sort,比较条件是姓名字符串的 <,按字典序升序排列。因此添加 Bob、Alice、Linda 后,显示顺序为 Alice、Bob、Linda;删除 Bob 后剩下 Alice、Linda。

只补充了这两个私有工具的实现,原有添加、删除、查询和显示接口及输出格式保持一致。

2. 如何逐步扩展为更实用的通讯录?(选答)

可以先增加修改联系人功能,修改姓名时复用查重逻辑,并重新排序;姓名、号码的有效性检查集中在固定位置,避免各处重复判断。

接着增加文件读写,让程序关闭后仍能保存联系人,并处理文件不存在、数据格式错误等情况。分组管理、模糊查找等功能可以通过新增接口逐步加入,保留原有接口,减少对测试代码和调用者的影响。

目前按姓名唯一识别联系人不适合真实的同名情况。进一步扩展时,可以为联系人设置稳定的唯一编号,姓名只用于显示和检索。

实验总结

这次实验让我把“对象拥有资源”与代码中的构造、复制和析构联系起来了。vector<Button>、通讯录中的 vector<Contact> 都可以把对象生命期交给容器管理;自己使用裸指针时,则要明确处理深拷贝、自赋值和异常安全。

const 不只是给变量加限制,也会影响返回引用的可写性、成员函数重载的选择。算法库能让查找、填充和复制更清楚,但不能代替范围检查和资源管理。矩阵的 set() 也说明了:一个裸指针本身不携带数组长度,接口参数“看起来匹配”不代表访问一定安全。

posted @ 2026-11-26 19:33  Ykxo  阅读(3)  评论(0)    收藏  举报