实验3

任务一

源代码

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

实验截图

image

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

  • 是组合关系,buttons_存储的是Button 值对象,不是 Button 指针。Button 对象的生命周期完全受 Window 控制:Window 创建时内部构造 Button;Window 销毁的时候,vector 析构,内部所有 Button 对象随之自动销毁。

问题2:: bool has_button(const std::string &label) const; 被设计为私有。 思考并回答:① 若将其改为公有接口,有何优点或风险? ② 设计类时,如何决策一个成员函数应为 public 还是 private?(可从“用户是否需要”、“是否仅为内部实现细节”、“是否易破坏对象状态”等角度分析。)

  • 1.优点:外部可以直接调用该函数判断按钮是否存在,不用自己遍历容器。
    风险:
    1)暴露内部业务判断细节,类内部容器一旦修改,外部所有调用has_button的代码全部失效;
    2)破坏封装,用户依赖内部实现细节,降低类可维护性;
    3)公有接口越多,后续版本兼容负担越重。
  • 2.public:是类对外提供服务,外部用户必须要调用才能完成业务功能;对外接口,不暴露内部实现。
    private:仅类内部其他成员函数调用,属于内部实现辅助细节,外部用户不需要直接使用;
    如果函数调用后,用户错误调用容易破坏对象内部状态,则应当私有。

Button的接口const std::string& get_label() const;返回const std::string&。对比以下两种接口设计在性能和安全性方面的差异并精炼陈述。接口1:const std::string& get_label() const;接口2:std::string get_label() const;

  • 接口1性能更优,禁止外部修改内部字符串;风险在于使用者不能保存该引用超过 Button 对象生命周期;
    接口2会发生字符串拷贝,性能损耗;但是返回独立副本,不存在悬空引用问题,安全性更高。

问题4:① 把window.hpp中所有 xx.push_back(Button(xxx))改成 xx.emplace_back(xxx),观察程序是否正常运行;查阅资料,回答两种写法的差别。② 用标准库改写window::has_button()实现,这样编写是否可以?查阅资料,简述std::any_of()功能、参数和返回值意义③ 用标准库改写window::click_button()实现,这样编写是否可以?查阅资料,简述std::find_if()功能、参数和返回值意义

  • 1.可以运行,
    push_back(Button(xxx)):先在外部构造临时Button对象,再把这个临时对象移动或拷贝存入 vector 容器。
    emplace_back(xxx):在 vector 容器内存空间直接原位构造 Button 对象,把参数直接传给 Button 构造函数,消除临时对象,减少拷贝或移动,效率更高。

  • 2.可以正常运行:
    参数:first起始迭代器,last末尾后迭代器,pred谓词(返回 bool 的可调用对象 /lambda)。
    功能:遍历 [first,last) 区间,只要任意一个元素满足谓词 pred 返回 true,函数整体返回 true;全部不满足返回 false。

  • 3.改法合法
    参数:起始迭代器 first,尾后迭代器 last,谓词 pred。
    功能:遍历区间,返回第一个满足谓词条件元素的迭代器;没有找到返回last尾后迭代器。程序判断返回迭代器不等于 end,代表找到按钮,调用click();否则输出没有该按钮。

任务2

源代码:

点击查看代码
#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中这两行代码分别完成了什么构造? v1、v2 各包含多少个值为 42 的数据项?

  • 调用 vector带初值的构造函数,创建 v1,5 个元素全部初始化为 42。
  • 调用 vector 的拷贝构造函数,用 v1 完整拷贝生成 v2。拷贝之后 v2 也有5 个值 42 的数据项。

问题2:测试模块2中这两行代码执后,v1.size()v2.size()、v1[0].size()分别是多少?

  • 分别为2,2,3

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

  • 下标合法时效果完全相同,operator[]下标运算符:不做越界检查。索引越界直接访问非法内存,未定义行为,程序可能崩溃、乱码。
    at(index):会做下标范围检查;如果下标越界,std::out_of_range 异常,安全性更高。

问题4::测试模块2中执行v1[0].push_back(-1); 后①用以下两行代码,能否输出-1?为什么?②r定义成用const &类型接收返回。

  • 1.可以,v1[0]返回子 vector 引用,r 绑定这个子 vector;执行v1[0].push_back(-1)之后该子 vector 末尾增加‑1;r 是对这个子 vector 的引用,r.size () 是修改之后的大小,r[r.size()-1]访问新增的‑1。
  • 2.- 内存优势:采用引用,不会拷贝整个 vector 对象,直接绑定原有对象,节省复制内存与时间开销。
    限制:r 是 const 引用,不能通过 r 修改容器内元素,不能调用非 const 成员函数。

问题5:① 标准库模板类vector 的复制构造函数实现的是深拷贝还是浅拷贝?② vector::at() 接口思考:当 v是vector 时,v.at(0) 返回值类型是什么?当v是const vector 时v.at(0) 返回值类型又是什么?据此推断标准库std::vector 的at() 是否必须提供带 const 修饰的重载版本?

  • 1.vector 拷贝构造实现深拷贝。拷贝之后 v1、v2 拥有两套完全独立内存;修改原 vector 元素,拷贝副本不受影响。
  • 2.当vector v,v.at(0)返回int&;当const vector v(const 对象),v.at(0)返回`const int&(const 引用,禁止修改)。
    必须提供 const 重载版本。const 对象只能调用 const 修饰成员函数;如果没有 const 版本 at,const vector 对象无法调用 at 访问元素。

任务3

源代码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

源代码vectorlnt.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_;
}

运行截图

image

问题1:当前代码中,vectorInt 接口assign() 现是安全版本。如果把assign 实现改成版本2,运行程序,提供运行截图,观察test3模块输出结果有无异常。逐条指出版本2存在的安全隐患和缺陷。(提示:对比两个版本,找出差异化代码,加以分析)

  • 缺陷:缺少自赋值判断if(this == &vi) return *this;
    第一步执行delete[] pdata_;释放了本对象的内存,而 vi 就是 * this;vi.pdata_此时已经变成野指针。后续循环读取vi.pdata_[i]`访问已经释放内存,发生未定义行为,程序崩溃或者乱码。
    安全版本先判断this == &vi,如果是自赋值直接 return,不会执行 delete。

问题2:① static_cast<const vectorInt*>(this)的作用是什么?转换前后this的类型分别是什么?转换目的?②const_cast<int&>的作用是什么?转换前后的返回类型分别是什么?转换目的?

  • 1.转换前this:vectorInt(普通对象指针)
    转换后:const vectorInt
    ,给 this 指针增加 const 限定。
    作用:把当前对象视为 const 对象,调用 const 版本的 at () 成员函数,复用已经写好的越界检查逻辑,消除两份重复代码。
  • 2.转换前返回值:const int& const 引用
    转换后返回:int&普通引用
    作用:剥离 const 属性,返回可修改的左值引用给非 const at 函数调用者。

问题3:以下代码片段,分析编译器如何选择重载版本,并总结这两种重载适配什么使用场景。

  • 非 const 对象 v1,优先调用非 const 修饰成员函数 begin ();返回普通指针,得到可写迭代器,可以修改容器元素。
  • const 对象 v2,只能调用 const 限定成员 begin ();返回 const 指针,只读迭代器,禁止修改容器内容。

问题4:构造函数vectorInt(int n, int value)、vectorInt(const vectorInt &vi)及接口assign包含内存块的赋值或复制操作。使用算法库改成如下写法是否可以?回答这3行更新代码的功能。

  • 可以使用的。需要包含头文件。
  1. std::fill_n(pdata_, n_, value);:从 pdata_起始地址开始,写 n_个 value 值,批量给数组赋值,替代 for 循环赋值。
  2. std::copy_n(vi.pdata_, vi.n_, pdata_);:从源地址 vi.pdata_复制 n_个 int,复制到目标 pdata_;完成深拷贝复制。
  3. std::copy_n(vi.pdata_, vi.n_, ptr);:将 vi 的数据拷贝到新分配的 ptr 堆内存;后续替换 this 对象内部 pdata_,完成 assign 深拷贝。

任务4

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_;
    int total = n_rows_ * n_cols_;
    pdata_ = new double[total];
    std::copy_n(x.pdata_, total, 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");
    std::copy_n(pvalue, size, pdata_);
}

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

// 修复:原来 i> n_rows_ → i >= n_rows_;j同理
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];
}

// 非const版本at,复用const at,使用static_cast + const_cast
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";
    }
}

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

task4源代码

点击查看代码
#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的值按行为矩阵m1赋值

    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()接口,确保该接口使用时更安全、可靠。

  • 存在风险:这个函数接收裸指针,没有办法校验传入数组真实长度。矩阵总元素数量是 rows cols。如果外部实际数组长度小于 size,会发生数组越界访问,读取到数组后面的未知垃圾内存,程序行为未定义,可能乱码、崩溃。指针本身不带长度信息,函数无法感知外部缓冲区真实大小。
    优化:改成std::span,span 自带长度信息,内部可以判断:if(span.size() != rows()*cols()) 直接抛异常。

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

源代码task.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

posted @ 2026-11-21 17:06  早上起床拉肚子  阅读(3)  评论(0)    收藏  举报