实验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 <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

三、回答问题

问题一:

是。buttons_ 的声明方式是 std::vector<Button>,里面存储的是 Button 对象(值);
对象生命周期管理方面,Window 对象被销毁时,其成员 buttons_ 也会被自动销毁,进而调用 vector 的析构函数,释放内部所有的 Button 对象。Window 不需要(也无法)手动去 delete 这些按钮,按钮的生死完全依附于窗口。这符合组合关系“同生共死”的特征。

问题二:

①
优点
:如果外部有检查按钮是否存在的需求,那么它可以直接调用has_button查询。
风险:破坏了封装。has_button 原本只是内部 add_button 的辅助工具,外部并没有这个需求。公有化会无端扩大类的接口,而绝大多数情况下,接口越多维护成本越高。

② 设计类时,如何决策一个成员函数应为 public 还是 private?

  • 用户是否需要:外部必须使用的功能设为 public。
  • 是否为内部实现细节:像 has_button 这种辅助工具,只是为了内部实现细节,配合类内其他函数(add_button)使用,外部不需要,设为 private。
  • 是否易破坏对象状态:可能被外部滥用、导致对象内部状态混乱的接口必须私有化。(个人理解类似恶意攻击网站)

问题三:

  • 性能差异:接口2(std::string)会增加复制开销。
  • 安全性差异:接口1返回 const 引用,调用者只能读取,不能修改内部数据;接口2返回的是副本,随便改都不影响原对象。
    总之接口1更高效。

问题四:

① 程序正常运行。
push_back 需要先构造一个临时的 Button 对象,然后再将其拷贝(或移动)进容器中;emplace_back 则是直接在容器内存中原地构造 Button 对象,省去了临时对象的创建和拷贝/移动开销,效率更高。(个人理解现在编译器实现了类似emplace_back的优化,但在查询ai中得知编译器的优化并不是万能的,emplace_back 在某些场景下依然具有不可替代的优势,这里不多加赘述)

② 可以。
std::any_of() 用于判断给定区间内是否存在至少一个元素满足特定条件。它的参数包括:起始迭代器、结束迭代器、一个返回 bool 的一元谓词(如 lambda 表达式)。返回值为 true 表示存在满足条件的元素,否则返回 false。(一元谓词就是一个“只接收一个参数,并返回布尔值”的函数)

③ 可以。
std::find_if() 用于在区间内查找第一个满足特定条件的元素。参数为起止迭代器和一元谓词。返回值是指向第一个满足条件元素的迭代器;如果没找到,则返回结束迭代器(end())。

问题五:

  • 瓶颈:因为GUI的交互瓶颈取决于人,哪怕疯狂连点这种速度对计算机来说也微不足道
  • 变化:std::map 会对 key(label 为 key)自动排序。所以 display() 打印出的按钮顺序会变成按字符串字典序排列,而不再是最初添加到窗口的先后顺序。
  • 是否可接受:取决于业务需求。如果界面需要保持添加时的顺序(如先添加的在上),则不可接受;如果无所谓顺序或本就希望排序,则可以接受。

任务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

三、回答问题

问题一:

普通构造和拷贝构造,都包含五个。

问题二:

  • v1.size() 是 2
  • v2.size() 是 2
  • v1[0].size() 是 3

问题三:

  • 能。两者都能把 v1 的第一个元素修改为 -1。
  • v1[0]不做边界检查,但运行效率最高。
  • v1.at(0) 进行边界检查,更安全,但每次访问有轻微的性能损耗。

问题四:

①能。
原因:v1[0].push_back(-1) 后,v1[0]从{1, 2, 3}变成了{1, 2, 3,-1},而r绑定了v1[0],也就是绑定了第一个数组{1, 2, 3,-1},r.size()-1也就是-1的下标,所以r[r.size()-1] = -1

② 优势与限制:

  • 优势:const & 省去了拷贝整个内层 vector 的内存和时间开销。
  • 限制:不能修改它(如 r.push_back(2) 或 r[0] = 9 都是非法的)。同时,引用的生命期受限于原对象,如果原 v1 被销毁,r 就会变成悬空引用(野引用)。

问题五:

①深拷贝
②int& (非 const 引用)和 const int& (const 引用)
(PS:v[0]和 at() 返回值类型完全一致)
必须带有const的重载版本,因为const对象只能调用const函数,如果不带的话,那么const vector对象就无法调用at()方法。

任务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(int n, int value): n_{n}, pdata_{new int[n](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(const vectorInt &vi): n_{vi.n_}, pdata_{vi.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::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

三、回答问题

问题一:

image

版本2没有检查传入的对象是否就是自己,不安全。因为如果传入的对象就是自身,那么在第一步delete[] pdata_就会销毁自身数据,导致数据丢失。

问题二:

**①static_cast<const vectorInt*>(this) 的作用?转换前后 this 的类型?转换目的?

  • 作用:增加 const 属性(将当前指针转为指向常量的指针)。
  • 转换前后类型:转换前是 vectorInt* const;转换后变为 const vectorInt* const。
    (后一个const是因为在成员函数内部,this 指针的实质就是一个常量指针,不能改变指向,永远指向该对象)
  • 目的:为了调用 const 版本的 at() 成员函数。因为如果不加const,编译器会优先匹配非const版本,也就是该函数自身,那么就会陷入无限递归。

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

  • 作用:去除 const 属性。
  • 转换前后类型:转换前,内层 at() 的返回类型是 const int&;转换后,返回类型变为 int&.
  • 转换目的:因为调用的 const 版本 at() 返回的是只读引用,而当前非 const 版本的 at() 需要返回可读可写的 int& 供外部修改。

问题三:

①

  • v1.begin():调用的是非 const 版。
  • v2.begin():调用的是 const 版本。
  • 使用场景:非 const 版本给普通的 vectorInt 对象使用,允许通过迭代器修改元素。const 版本给 const vectorInt 对象用。
    ② 原本以为迭代器是非常复杂的对象,但 vectorInt 直接返回 int* 和 const int*,说明迭代器的底层本质就是指针。 这也解释了为什么迭代器支持 ++、* 等操作——因为指针就天然支持这些操作啊。而且迭代器更安全。

问题四:

可以。 功能如下:

  1. std::fill_n(pdata_, n_, value);
    从指针 pdata_ 开始,将连续的 n_ 个元素全部赋值为 value。
  2. std::copy_n(vi.pdata_, vi.n_, pdata_);
    从源指针 vi.pdata_ 开始,复制 vi.n_ 个元素到目标指针 pdata_ 所指向的内存中。
  3. std::copy_n(vi.pdata_, vi.n_, ptr);
    同样是从源指针 vi.pdata_ 复制 vi.n_ 个元素到目标的临时指针 ptr新申请的内存中。

四、一些新感悟

  1. 返回值是引用\指针的时候,const函数必须有双const,不然会自相矛盾
  2. pdata_ 是 指向连续内存的指针 而非 数组指针
  3. 深浅拷贝对比
//深拷贝
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(const vectorInt &vi): n_{vi.n_}, pdata_{vi.pdata_} {} 
// 错误:把原指针直接赋给新指针
  1. 对于无需修改值的函数而言,const适用范围更广

  2. 在·at()接口中的返回值是(非)const引用,为什么可以return pdata_[index] ?
    ①关于引用:
    C++ 规定:左值可以用来初始化引用。
    所以,当你的函数签名是 int& at(...) 时,编译器看到你返回了一个左值 pdata_[index],它会自动把这个左值绑定到你要返回的引用上,交出去。
    ②关于const:
    因为 C++ 允许在函数返回时,自动进行“隐式类型转换”。
    当函数声明为返回 const int& 时,编译器会把 pdata_[index] 这个非 const 的 int,加上 const 属性,然后作为 const int& 返回。这在 C++ 里是完全合法的,因为把一个可修改的对象绑定到 const 引用上,是允许的(这叫收缩权限)。

  3. 为什么vectorInt& assign(const vectorInt &vi);要返回引用?
    因为 assign 的功能是修改对象自身(将传入对象的数据深拷贝给自己)。这个修改动作在函数体内部已经全部完成,返回值只是把“修改后的自己”交出去。

  • 如果不加 &(按值返回):
    为了不浪费返回的那个临时对象,调用者被迫写成:v2 = v2.assign(v1);
    劣势:
    1. 多余深拷贝:assign 内部已经申请了新内存完成赋值,结果 return 时还要再触发一次拷贝构造,克隆出一个临时对象。
    2. 再次赋值:外部接收后,还要调用一次 operator=,把临时对象再拷贝回 v2。
    3. 整个过程“脱裤子放屁”,经历了三次深拷贝。
  • 如果加 &(返回引用):
    调用者直接写:v2.assign(v1);
    优势:
    1. 语义自洽:函数内部已经修改了自身,返回值直接返回 *this 的引用即可,符合人类的“直接操作”习惯。
    2. 零拷贝:return *this; 只是把 v2 的地址(门牌号)传出去,没有发生任何内存分配与拷贝。
      结论:返回引用完美契合了 assign “修改自身”的功能定位,彻底避免了返回值带来的额外深拷贝灾难。

任务4

一、源代码

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 <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) {
	pdata_ = new double[x.n_rows_*x.n_cols_];
	for(auto i = 0; i < x.n_rows_*x.n_cols_; ++i)
        pdata_[i] = x.pdata_[i];
}

// 待实现:释放指针指向的内存资源
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);
}

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)对应的数据项引用(越界则抛出异常)
// 参考前一个接口和task3的问题2
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++){
    		std::cout << pdata_[i * n_cols_ + j] << " ";
		}
		std::cout << "\n";
	}
}

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的值按行为矩阵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[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

三、回答问题

问题一

  • 潜在风险:double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};后面没初始化的部分会自动补0,但也有超出风险;而double x[5] = {1, 2, 3, 4, 5};仅有5个元素,输入2 3或2 5的矩阵大小都超过了5,所以会读到越界的垃圾数据。在set()接口中的1if(size != n_rows_ * n_cols_)根本没有实际作用,输入的m和n都由操作者决定,而矩阵容量n_rows_ * n_cols_ 是n*m,而size也是n*m,二者一定相等,所以这个判断根本无法阻止越界。
  • 优化方案:
    task4.cpp 的 test1() 内部:
  1. 将 double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};改为:
      std::vector<double> x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};//顶部添加`#include <vector>`
    
  2. 将所有 m1.set(x, n*m); 等调用(包括 m2、m3 的 set)统一改为:
    m1.set(x.data(), static_cast<int>(x.size()));
    

image

问题二

换成 vector<double>:自带析构(可以自动释放内存不用手动delete,规避了忘记delete造成内存泄漏的风险)拷贝构造、赋值、深拷贝。而double* pdata_ 都得自己写。
而关于零成本抽象通过查阅资料我了解到的是:

  1. 你不用的功能,不为它付出任何运行时代价(时间、内存)
  2. 你正在使用的功能,手写底层代码也写不出比它更快的机器码

总结下来就是外壳会不会在程序运行的时候拖后腿。


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

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

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(); // 按姓名字典序升序排序通讯录

    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(int i=0;i<contacts_.size();i++){
		if(contacts_[i].get_name()==name)
			return i;
	}
	return -1;
}


// 待补足2:void ContactBook::sort();实现
// 按姓名字典序升序排序通讯录
inline void ContactBook::sort(){
	int i,j;
	Contact t("t","1");
	for(i=0;i<contacts_.size()-1;i++){
		for(j=0;j<contacts_.size()-1-i;j++){
			if(contacts_[j].get_name()>contacts_[j+1].get_name()){
				t = contacts_[j];
				contacts_[j] = contacts_[j+1];
				contacts_[j+1] = t;
			}
		}
	}
}

二、运行结果截图

image

posted @ 2026-11-23 19:37  忧郁蛋挞  阅读(0)  评论(0)    收藏  举报