实验3 类和对象_基础编程2

四、实验结论

实验任务 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 <algorithm>
#include <iostream>
#include <string>
#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_.emplace_back("close");
}

inline void Window::display() const {
    const std::string border(40, '*');
    std::cout << border << '\n';
    std::cout << "window : " << title_ << '\n';
    std::vector<Button>::size_type number = 1;
    for (const auto &button : buttons_) {
        std::cout << number << ". " << button.get_label() << '\n';
        ++number;
    }
    std::cout << border << '\n';
}

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

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

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

inline void Window::click_button(const std::string &label) {
    auto button = std::find_if(buttons_.begin(), buttons_.end(),
                               [&label](const Button &candidate) {
                                   return candidate.get_label() == label;
                               });
    if (button == buttons_.end()) {
        std::cout << "no button: " << label << '\n';
        return;
    }
    button->click();
}

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 << "Window and button demo\n";
    test();
    return 0;
}

运行结果

![任务 1 窗口与按钮]
task1

窗口刚建好就有一个 close 按钮。程序加了两次 add,第二次提示按钮已存在,列表里也只显示了一次。调用 close() 时,先输出窗口名,再找到并点击 close 按钮。

问题与思考

  1. Window 和 Button 的关系。 是组合关系。buttons_ 是 std::vector<Button>,存的是按钮对象本身。一个窗口销毁时,它的 buttons_ 也会销毁,其中的按钮跟着销毁。
  2. has_button() 的访问权限。 设成 public 后,外部可以先查按钮是否存在,比如决定是否显示某个操作。这个函数是只读的,调用它本身不会改动窗口状态,不过公开后就要为外部调用者一直维护这个接口。目前添加按钮时会在内部查重,外面只用调用 add_button() 就够了,所以我把查找留在 private 里。
  3. get_label() 的返回类型。 返回 const std::string& 时直接读成员,省去复制,也不能通过这个引用改标签。引用要在按钮对象还有效时使用,比如装着按钮的 vector 扩容导致原元素失效后,就不能再用之前取得的引用。返回 std::string 则得到一份独立的字符串,会有复制开销,原按钮销毁后仍然可以使用这份字符串。
  4. 三个标准库函数的替换。 分别改动并运行后,测试的窗口显示和关闭结果一致。
    • push_back(Button(label)) 先构造临时按钮,再把它移入容器(只有可用的拷贝构造时也可拷贝)。emplace_back(label) 用 label 在容器的位置直接构造按钮。两种方式遇到扩容时,容器仍可能需要移动或复制旧元素。C++ 标准草案:vector 插入操作
    • std::any_of(first, last, pred) 判断 [first, last) 中有没有元素满足 pred。本题的谓词是“按钮标签等于给定标签”,有匹配就返回 true,没有就返回 false。C++ 标准草案:any_of
    • std::find_if(first, last, pred) 用相同的区间和谓词,返回第一个匹配元素的迭代器。没找到时返回 last,所以要先检查迭代器是不是 buttons_.end(),再调用 click()。C++ 标准草案:find_if
  5. 按钮较多时的查找。 线性查找最坏要把按钮都看一遍。上百个按钮是否会拖慢程序,还得看查找频率和实际耗时。如果用 std::map<std::string, Button> 按标签查找,复杂度为 O(log n),按容器顺序显示时会变成按标签排序。要保留原来的按钮布局,就得另外保存显示顺序。

实验任务 2 验证 vector 的深拷贝

程序源码

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] Copying a vector<int>\n";
    test1();
    std::cout << "\n[2] Copying nested vectors\n";
    test2();
    return 0;
}

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

    std::cout << "After copying\n";
    std::cout << "v1: ";
    output1(v1);
    std::cout << "v2: ";
    output1(v2);

    v1[0] = -1;
    std::cout << "After changing 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 << "After copying\n";
    std::cout << "v1:\n";
    output3(v1);
    std::cout << "v2:\n";
    output3(v2);

    v1[0].push_back(-1);
    std::cout << "After appending to v1[0]\n";
    std::cout << "v1:\n";
    output3(v1);
    std::cout << "v2:\n";
    output3(v2);

    const std::vector<int> &r = v1[0];
    std::cout << "Last element through r: " << r[r.size() - 1] << '\n';
}

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

void output2(const std::vector<int> &v) {
    for (auto it = v.begin(); it != v.end(); ++it) {
        if (it != v.begin()) {
            std::cout << ", ";
        }
        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);
    }
}

运行结果

![任务 2 vector 拷贝测试]
task2

第一组把 v1 的第一个数改成 -1,v2 里还是五个 42。第二组向 v1 的第一行追加 -1,只有原来的第一行变长,v2 第一行仍然是 1, 2, 3。

问题与思考

  1. 两种构造。 v1(5, 42) 会构造五个值都为 42 的元素。下一句 const std::vector<int> v2(v1) 用 v1 拷贝构造 v2。这两句刚执行完时,两边各有五个 42。
  2. 嵌套容器的大小。 初始化并拷贝后,v1.size() 和 v2.size() 都是 2,因为外层一共两行,v1[0].size() 是 3。执行追加后,第一行的大小才变成 4。
  3. [] 和 at()。 实际把赋值换成 v1.at(0) = -1 后,输出和原来相同,下标 0 在两种写法里都指向首元素。区别在于 at() 会检查范围,越界就抛出 std::out_of_range。在本实验的 C++11 下,[] 越界属于未定义行为。
  4. 常量引用 r。 能输出 -1。执行完追加再写 const std::vector<int> &r = v1[0];,r 直接引用第一行,r[r.size() - 1] 取的就是追加进去的末尾元素。用引用会省掉复制整行所需的空间,只能通过它读取元素。外层 vector 扩容等操作可能使行对象的引用失效。
  5. 拷贝和 at() 的重载。 从两组结果可以看出,这里的 vector<int> 和嵌套 vector 都实现了深拷贝,嵌套的每一行也复制了自己的数据。普通 vector<int> 的 at() 返回 int&,可以直接给元素赋值。常量 vector<int> 调用的是 const 版本,得到 const int&,可以读元素。要同时支持这两种访问,就需要提供两种重载。C++ 标准草案:序列容器要求

实验任务 3 自定义动态数组

vectorInt 用长度和一个 int* 管理动态数组。测试分三步,先看拷贝构造,再看 assign(),最后把同一个对象传给自己的 assign()。测试程序用 at() 和指针各写了一种遍历方式。

程序源码

vectorInt.hpp

#pragma once

#include <algorithm>
#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);
    vectorInt& operator=(const vectorInt &vi);

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

private:
    static int* allocate(int n);
    int n_;
    int *pdata_;
};

inline int* vectorInt::allocate(int n) {
    if (n < 0)
        throw std::invalid_argument("negative vector size");
    return n == 0 ? nullptr : new int[n];
}

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

inline vectorInt::vectorInt(int n) : vectorInt(n, 0) {
}

inline vectorInt::vectorInt(int n, int value) : n_(n), pdata_(allocate(n)) {
    if (n_ != 0)
        std::fill_n(pdata_, n_, value);
}

inline vectorInt::vectorInt(const vectorInt &vi) : n_(vi.n_), pdata_(allocate(n_)) {
    if (n_ != 0)
        std::copy_n(vi.pdata_, n_, pdata_);
}

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 index out of range");
    return pdata_[index];
}

inline int& vectorInt::at(int index) {
    return const_cast<int&>(static_cast<const vectorInt*>(this)->at(index));
}

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

    int *new_data = allocate(vi.n_);
    if (vi.n_ != 0)
        std::copy_n(vi.pdata_, vi.n_, new_data);

    delete[] pdata_;
    n_ = vi.n_;
    pdata_ = new_data;
    return *this;
}

inline vectorInt& vectorInt::operator=(const vectorInt &vi) {
    return assign(vi);
}

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

task3.cpp

#include "vectorInt.hpp"

#include <iostream>
#include <limits>

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

void output2(const vectorInt &vi) {
    for (auto it = vi.begin(); it != vi.end(); ++it) {
        if (it != vi.begin())
            std::cout << ", ";
        std::cout << *it;
    }
    std::cout << '\n';
}

void test1(int 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);
    const vectorInt x3(x2);
    if (n > 0)
        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 << "Before changing y:\n";
    std::cout << "x: ";
    output2(x);
    std::cout << "y: ";
    output2(y);

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

void test3() {
    vectorInt x(5, 42);
    std::cout << "Before x.assign(x): ";
    output2(x);
    x.assign(x);
    std::cout << "After  x.assign(x): ";
    output2(x);
}

int main() {
    int n = 0;
    std::cout << "Test 1: construction and copy\n";
    std::cout << "Enter n: ";
    if (!(std::cin >> n) || n < 0 || n > std::numeric_limits<int>::max() / 10) {
        std::cerr << "Invalid size.\n";
        return 1;
    }
    test1(n);

    std::cout << "\nTest 2: assignment from a const object\n";
    test2();

    std::cout << "\nTest 3: self-assignment\n";
    test3();
    return 0;
}

运行结果

![任务 3 正常版 输入 7]
task3

![任务 3 assign 版本 2,输入 7]

task3-assign-v2

输入 7。拷贝后把 x2 的第一个数改为 -1,x3 的七个数都是 42。给 y 赋值以后再改 y,也只有 y 的第一个数变了。安全版测试 3 在自赋值前后都输出五个 42。

问题与思考

1. 版本 2 的 assign() 有什么隐患?

对照实验把正常版本中的 assign() 换成题目给的版本 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;
}

测试 2 的 x 和 y 是两个对象,源数组还在,结果正常。到了测试 3,自赋值前是五个 42,这次执行完以后前四项都变了,最后一项碰巧还是 42。

  • x.assign(x) 让 vi 和 *this 指向同一个对象。旧数组先被释放,随后 pdata_ 被换成新数组,vi.pdata_ 也就指向这块新数组。循环读到的是新数组里还没初始化的 int,行为未定义。偶尔输出原值也说明不了这一写法有效。
  • 对两个不同的对象来说,先删除目标的旧数据一样有风险。如果 new 抛出异常,目标原来的数据已丢失,成员指针仍是被释放的地址,析构时还可能再释放一次。

安全版遇到 this == &vi 就返回。一般赋值先申请新空间并复制,最后才删旧数组、更新成员。类里也让 operator= 调用这个版本,避免直接写 y = x 时只复制指针。

2. 非 const 的 at() 为什么要做两次转换?

非 const 成员函数里的 this 类型是 vectorInt*。static_cast<const vectorInt*>(this) 得到指向同一对象的 const vectorInt*,通过它调用 at() 就会选中只读重载,边界检查只写一遍。只读重载返回 const int&。外面的 const_cast<int&> 得到同一个元素的可写引用,原来调用这个重载的是普通对象,所以可用它改元素。 C++ 标准草案的类型转换说明

3. begin() 和 end() 会选中哪个重载?

对 vectorInt v1(5),v1.begin() 调用普通重载,auto it1 推导成 int*,解引用后可以修改元素。对 const vectorInt v2(5),v2.begin() 调用只读重载,auto it2 是 const int*。通过 const vectorInt& 访问也选只读版。end() 采用同样的规则,它只用来判断遍历是否结束。这里的元素放在连续内存里,原始指针已经能用 +、++、* 完成遍历。标准库里也有不使用原始指针实现的迭代器,例如链表的迭代器。

4. 三段循环可以用标准算法替换吗?

可以,程序使用了 <algorithm> 中的这两个算法。填充构造用 fill_n(pdata_, n_, value) 给从 pdata_ 开始的 n_ 个元素写入初值。拷贝构造用 copy_n(vi.pdata_, n_, pdata_) 把源对象的数据复制到新对象的数组。赋值用 copy_n(vi.pdata_, vi.n_, new_data) 先复制到新申请的空间,复制结束再替换旧数组。 C++ 标准草案的填充算法 C++ 标准草案的复制算法

实验任务 4 实现动态矩阵

矩阵按行存在同一个 double 数组里,所以第 i 行第 j 列对应 i * n_cols_ + j。方阵构造交给普通矩阵构造去做,拷贝构造自己申请一份空间。测试程序分别验证行列排列和拷贝以后能不能独立修改。

程序源码

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_;    // 数据区
};

matrix.cpp

#include "matrix.h"

#include <algorithm>
#include <iostream>
#include <limits>
#include <stdexcept>

namespace {
int checked_size(int rows, int cols) {
    if (rows < 0 || cols < 0)
        throw std::invalid_argument("matrix dimensions must be non-negative");
    if (rows != 0 && cols > std::numeric_limits<int>::max() / rows)
        throw std::length_error("matrix size is too large");
    return rows * cols;
}
}

Matrix::Matrix(int n_rows, int n_cols, double value)
    : n_rows_(n_rows), n_cols_(n_cols),
      pdata_(new double[checked_size(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[n_rows_ * 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 the matrix");
    if (size == 0)
        return;
    if (pvalue == nullptr)
        throw std::invalid_argument("source data is null");
    std::copy_n(pvalue, size, pdata_);
}

void Matrix::clear() {
    std::fill_n(pdata_, n_rows_ * n_cols_, 0.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) {
        for (int j = 0; j < n_cols_; ++j) {
            if (j != 0)
                std::cout << ", ";
            std::cout << at(i, j);
        }
        std::cout << '\n';
    }
}

task4.cpp

#include "matrix.h"

#include <iostream>
#include <stdexcept>

void output(const Matrix &m, int row_index) {
    if (row_index < 0 || row_index >= m.rows())
        throw std::out_of_range("row index out of range");
    for (int j = 0; j < m.cols(); ++j) {
        if (j != 0)
            std::cout << ", ";
        std::cout << m.at(row_index, j);
    }
    std::cout << '\n';
}

bool test1() {
    const double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    const int capacity = sizeof x / sizeof x[0];

    int n = 0, m = 0;
    std::cout << "Enter n and m: ";
    if (!(std::cin >> n >> m) || n <= 0 || m <= 0) {
        std::cerr << "Please enter two positive dimensions.\n";
        return false;
    }
    if (n > capacity / m || n > capacity / n) {
        std::cerr << "Not enough source values for these dimensions.\n";
        return false;
    }

    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 << " x " << m << "):\n";
    m1.print();
    std::cout << "m2 (" << m << " x " << n << "):\n";
    m2.print();
    std::cout << "m3 (" << n << " x " << n << "):\n";
    m3.print();
    return true;
}

void test2() {
    Matrix m1(2, 5, -1);
    const Matrix m2(m1);
    std::cout << "m1:\n";
    m1.print();
    std::cout << "m2 (copy of m1):\n";
    m2.print();

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

    std::cout << "After changing m1:\n";
    std::cout << "m1[0]: ";
    output(m1, 0);
    std::cout << "m2[0]: ";
    output(m2, 0);
}

int main() {
    std::cout << "Test 1: rectangular and square matrices\n";
    if (!test1())
        return 1;

    std::cout << "\nTest 2: copy construction and update\n";
    test2();
    return 0;
}

运行结果

![任务 4 正常版,输入 3 2]
task4
![任务 4 短数组对照,输入 2 3]
task4-short-array

正常测试输入 3 2。三个矩阵的尺寸是 3×2、2×3 和 3×3。第二组测试把 m1 清零后更新前两项,m1 第 0 行显示 1, 2, 0, 0, 0,拷贝出的 m2 第 0 行依然全是 -1。

问题与思考

下标边界

原代码用 i > n_rows_ || j > n_cols_,会放过刚好等于行数或者列数的下标。用 3×2 矩阵举例,at(0, 2) 可能误取下一行第 0 列,at(3, 0) 则会访问到整块数据的外面。这里改成 i >= n_rows_ || j >= n_cols_,同时保留对负下标的检查。普通版 at() 复用只读版的检查。

set() 的风险

对照程序把源数组改成 double x[5] = {1, 2, 3, 4, 5},输入 2 3。调用 set(x, n * m) 时传入 6,也刚好等于矩阵需要的元素数,原有的长度判断因此会通过。实际的源数组只到 x[4],读第六项已经越界。这次矩阵的最后一项显示成了 2.10263e-317,重跑时可能读到别的值,程序也可能直接出错。

正常测试里,x 还是数组时就能用 sizeof x / sizeof x[0] 算出它的实际长度,所以我先比较数组容量和三个矩阵需要的数据量,再传指针给 set()。这个做法也能拦住输入过大导致的乘法溢出。

以后如果允许改接口,可以接收 const std::vector<double>& values,在函数内比较 values.size() 和矩阵元素个数,调用处就不用再手写长度。如果还要直接传定长数组,也可以用 template <std::size_t N> void set(const double (&values)[N]),让编译器推导数组长度。这里按题目保留 matrix.h 的接口。 C++ 标准草案的数组形参规则

换成 vector<double> 会怎样?

如果内部改用 vector<double>,下标公式还能照用,元素仍然连续存放。vector 会自己处理元素的拷贝和释放,也能避免默认的 Matrix::operator= 只复制指针的问题。这个实验用的是拷贝构造 Matrix m2(m1)。原接口里的 set(const double*, int) 即使换了内部存储,还是得检查传进来的数组长度。

实验任务 5 简易通讯录

这题要补的是通讯录内部的查找和排序。Contact 保存单个联系人的姓名、电话,ContactBook 用 vector<Contact> 管理一组联系人。查找用 find_if,找到后用迭代器与起点的距离算下标。比较时直接用姓名字符串的 ==,所以区分大小写。排序时用 < 比较两个人的姓名,新联系人加进来以后,列表就会按姓名重新排好。

程序源码

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

inline int ContactBook::index(const std::string &name) const {
    auto it = std::find_if(contacts_.cbegin(), contacts_.cend(),
                           [&name](const Contact &contact) {
                               return contact.get_name() == name;
                           });
    if (it == contacts_.cend()) {
        return -1;
    }
    return static_cast<int>(it - contacts_.cbegin());
}

inline void ContactBook::sort() {
    std::sort(contacts_.begin(), contacts_.end(),
              [](const Contact &left, const Contact &right) {
                  return left.get_name() < right.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();
}

运行结果

![任务 5 通讯录增删查显]
task5

程序先加 Bob,再加 Alice 和 Linda,显示时 Alice 排在第一位。第二次添加 Alice 被拒绝,人数还是 3。查找 Bob 能看到他的记录,查找和删除 David 都提示找不到。删除 Bob 以后,只剩 Alice 和 Linda。

拓展思考

如果要加修改电话的功能,可以先复用 index() 定位联系人,再检查新号码的格式,最后更新这一条记录。要是也允许改姓名,就得先查重,改完再排序。文件存储可以给 ContactBook 增加读写接口,读文件时先检查字段,再把有效记录放进通讯录。模糊查找可以单独加一个接口,用 string::find 做部分匹配,原来的精确查找还能继续用。分组可以给联系人加分组字段,显示时按组筛选。

五、实验总结

任务 2 和任务 3 放在一起看,深拷贝就容易理解了。标准库的 vector 拷贝完以后,可以直接改原来的元素。自己管理数组时,就要先给副本申请空间,还得考虑 x.assign(x) 这种源和目标是同一个对象的情况。先复制再释放旧数组,顺序一换,结果就可能不一样。

矩阵那题让我更注意下标和数组长度。行号刚好等于行数也越界。把数组传给指针形参后,函数里拿不到它原来的长度,所以就算传进去的数字刚好等于矩阵元素个数,仍然要看调用处是不是真有那么多项。

posted @ 2026-11-26 12:35  睦紫米  阅读(11)  评论(0)    收藏  举报