实验3

实验任务1

源代码

点击查看代码
#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} {
}

点击查看代码
#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} {
}

点击查看代码
#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.是组合关系(has-a)。buttons_ 声明为 std::vector<Button,是以值方式持有 Button 对象(不是 Button* 指针),Button 对象作为 Window 的成员子对象存放在 vector 的连续内存中。
2.优点:外部可以复用"按名字查找按钮"的逻辑,无需外部自己再遍历一遍 vector,避免重复代码。
用户是否需要:外部确实需要、且属于这个抽象本身对外提供的能力 → public;只是内部干活的辅助 → private。
是否仅为内部实现细节:has_button 只服务于 add_button 查重,是内部实现细节 → private。
是否容易破坏对象状态:public 接口必须维护对象的不变量、行为稳定;只参与内部、误用易导致状态不一致的操作 → private。
3.返回 const string& 免去拷贝、性能更优,适合只读访问;返回 string 拷贝性能较差但得到独立副本、隔离性最好。本接口只读且对象生命周期受控,用 const& 更合适。
4.push_back(Button(xxx)):先构造一个临时 Button,再把它拷贝/移动进 vector,多一次临时对象构造与移动。
emplace_back(xxx):把参数直接转发给 Button 的构造函数,在容器内存中原地构造,省去临时对象,效率更高。
在 [first, last) 中查找第一个满足谓词的元素,返回指向该元素的迭代器;找不到返回尾后迭代器 last。判断 it != end() 后再 it->click(),找不到走 else 分支。
5.按钮数量大、点击频繁时,click_button 的 O(n) 线性查找会成为瓶颈(每次都从头遍历);但只有上百个时现代计算机仍能承受,瓶颈是否明显取决于访问频率。

实验任务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.v1(5, 42):指定大小+初值构造,构造一个含 5 个元素、初值全为 42 的 vector。
v2(v1):拷贝构造,用 v1 复制出一个独立副本 v2。
v1、v2 各含 5 个值为 42 的数据项。

2.v1.size() == 2(两个内层 vector)
v2.size() == 2(拷贝后行数相同)
v1[0].size() == 3(第一行 {1,2,3})

3.能实现同等效果。区别:operator[] 不做越界检查,越界属于未定义行为(快但不安全);at() 会检查下标范围,越界抛出 std::out_of_range 异常(安全,有轻微检查开销)。

4.能输出 -1。v1[0] 返回非 const 的 vector&,用 const vector& r 绑定该左值合法,r 引用的就是 v1[0] 本体;push_back(-1) 后 v1[0] 为 {1,2,3,-1},r.size()-1 == 3,r[3] 即 -1。实测输出 -1。
优势:只取别名、不拷贝整个 vector,省去分配内存和复制所有元素的开销,零拷贝零分配。
限制:r 是 const 引用,不能通过它修改对象(不能 r.push_back(...)、不能 r[i] = ...,也不能调用非 const 成员函数)。

5① 标准库 vector 的复制构造函数实现的是深拷贝:拷贝时另外分配内存并逐个复制元素,修改原对象不影响副本(test1 改 v1[0] 不影响 v2;test2 push_back 也不影响 v2,均已验证)。
② v 为非 const vector 时 v.at(0) 返回 int&;v 为 const vector 时返回 const int&。因此 at() 必须提供 const 重载版本:const 对象只能调用 const 成员,没有 const 版 at 就无法以只读方式访问其元素。

任务实验3

源代码

点击查看代码
#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_;
}
点击查看代码
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';
}
点击查看代码
// 版本2
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

问题

1.实测 test3 执行 x.assign(x) 后,每次运行输出的都是不同的垃圾值(例如 1494456006, 21868, 0, 0, 42、3212222, 21995, 0, 0, 42,多次运行结果各不相同),属于未定义行为,严重时会段错误。
安全版的正确做法:先 new 新块 → 从源复制到新块 → 再 delete[] 旧块 → 最后换指针;并先用自赋值判断直接返回,从根本上避免以上问题。
2.① static_cast<const vectorInt>(this):把 this 从 vectorInt(转换前)转换为 const vectorInt(转换后)。目的:在非 const 函数内显式调用 const 版 at();若直接 this->at(index),由于 this 是 vectorInt,会递归匹配到非 const 版本自身,造成无限递归。先转成 const 指针才能命中 const 重载。
② const_cast<int&>:把 const 版返回的 const int&(转换前)去掉 const,转为 int&(转换后)返回。目的:非 const 对象调用 at() 时要返回可修改的引用,同时逻辑复用 const 版本。仅因为对象本身是非 const,这样去 const 才安全。
3.① 编译器按对象是否 const 匹配重载:非 const 对象 v1 优先绑定非 const 版本,返回可读写的 int;const 对象 v2 只能调用 const 版本,返回只读的 const int。非 const 版供可修改对象遍历/修改;const 版供 const 对象、const 引用形参只读遍历,防止只读对象被意外修改。
②(选)拓展理解:迭代器本质是"能用统一接口(解引用、自增、比较)访问容器元素"的对象。原始指针本身就具备这些操作,所以可以直接当迭代器用;标准库迭代器只是进一步封装、屏蔽不同容器(链表、树)的底层差异,对外保持一致语义。
4.可以,已实测编译运行结果与原版一致。

实验任务4

源代码

点击查看代码
#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) {
}

// 待实现:释放指针指向的内存资源
Matrix::~Matrix() {
}

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

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

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

// 待实现:按行打印数据
void Matrix::print() const {
    
}
点击查看代码

点击查看代码
#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_;    // 数据区
};

image

问题

1.风险:set 只校验调用方传入的 size 是否等于 rows*cols,无法知道外部数组的真实长度。当外部数组更短却传了足够大的 size 时,校验仍然通过,但 copy_n 会越界读取。

实验任务5

源代码

点击查看代码
# 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(int i = 0; i < static_cast<int>(contacts_.size()); ++i)
        if(contacts_[i].get_name() == name)
            return i;

    return -1;
}


inline v
点击查看代码
#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();
}
点击查看代码
#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_;
}

image

问题

1,index() 线性查找姓名(== 区分大小写),sort() 用 std::sort 配合姓名比较谓词按字典序升序,新增后自动排序,重复添加、查找不存在、删除不存在均按预期提示。
2.引入 std::map/unordered_map 做姓名索引加速查找,加一层校验逻辑,对外接口保持兼容,便于维护。

posted @ 2026-11-26 14:38  d111kkk  阅读(3)  评论(0)    收藏  举报