实验3

一、实验任务1

源代码task1

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <string>
 5 
 6 class Button {
 7 public:
 8     Button(const std::string &label_);
 9     const std::string& get_label() const;
10     void click();
11 
12 private:
13     std::string label;
14 };
15 
16 Button::Button(const std::string &label_): label{label_} {
17 }
18 
19 inline const std::string& Button::get_label() const {
20     return label;
21 }
22 
23 inline void Button::click() {
24     std::cout << "Button '" << label << "' clicked\n";
25 }
button.hpp
 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <vector>
 5 #include <algorithm>
 6 #include "button.hpp"
 7 
 8 // 窗口类
 9 class Window{
10 public:
11     Window(const std::string &title_);
12     void display() const;
13     void close();
14     void add_button(const std::string &label);
15     void click_button(const std::string &label);
16 
17 private:
18     bool has_button(const std::string &label) const;
19 
20 private:
21     std::string title;
22     std::vector<Button> buttons;
23 };
24 
25 Window::Window(const std::string &title_): title{title_} {
26     buttons.push_back(Button("close"));
27 }
28 
29 inline void Window::display() const {
30     std::string s(40, '*');
31     std::cout << s << std::endl;
32     std::cout << "window : " << title << std::endl;
33     int cnt = 0;
34     for(const auto &button: buttons)
35         std::cout << ++cnt << ". " << button.get_label() << std::endl;
36     std::cout << s << std::endl;
37 }
38 
39 inline void Window::close() {
40     std::cout << "close window '" << title << "'" << std::endl;
41     click_button("close");
42 }
43 
44 inline bool Window::has_button(const std::string &label) const {
45     for(const auto &button: buttons)
46         if(button.get_label() == label)
47             return true;
48     
49     return false;
50 }
51 
52 inline void Window::add_button(const std::string &label) {
53     if(has_button(label))
54         std::cout << "button " << label << " already exists!\n";
55     else
56         buttons.push_back(Button(label));
57 }
58 
59 inline void Window::click_button(const std::string &label) {
60     for(auto &button:buttons)
61         if(button.get_label() == label) {
62             button.click();
63             return;
64         }
65             
66     std::cout << "no button: " << label << std::endl;
67 }
window.hpp
 1 #include "window.hpp"
 2 #include <iostream>
 3 
 4 void test(){
 5     Window w("Demo");
 6     w.add_button("add");
 7     w.add_button("remove");
 8     w.add_button("modify");
 9     w.add_button("add");
10     w.display();
11     w.close();
12 }
13 
14 int main() {
15     std::cout << "用组合类模拟简单GUI:\n";
16     test();
17 }
task1.cpp

运行结果截图

525575c3c6c02e3404caf320d756824e

问题1:这个范例中, Window 和 Button 是组合关系吗?
是。组合关系的核心特征是“整体与部分紧密关联,部分的生命周期完全依赖于整体”。范例中Window类包含存储Button类型的vector容器,Button作为Window的组成部分,其创建、销毁等生命周期均由Window类管理,符合组合关系的定义。
问题2: bool has_button(const std::string &label) const; 被设计为私有。 思考并回答:
(1)若将其改为公有接口,有何优点或风险?
优点:外部代码可直接调用该接口查询指定标签的按钮是否存在,满足功能验证、业务判断等直接使用需求,提升开发便捷性。

风险:1.破坏封装性:该函数属于Window类内部查询按钮的实现细节,公有化后会使外部代码依赖类的内部逻辑(如按钮的存储结构、查询规则),后续若修改内部实现(如更换存储容器、调整查询逻辑),会导致外部依赖代码失效;2.存在数据一致性风险:并发场景下,外部调用得到 “按钮存在” 的结果后,该按钮可能被Window内部删除或修改,导致外部基于查询结果的后续操作出现逻辑错误;3.增加维护成本:接口公有化后需长期保证兼容性,限制了类内部优化的灵活性。

(2)设计类时,如何判断一个成员函数应为 public 还是 private?(可从“用户是否需要”、“是否仅为内部实现细节”、“是否易破坏对象状态”等角度分析。)
若为类对外核心功能,用户需直接调用,设为public;若仅为内部辅助实现,不对外暴露细节,设为private;若可能破坏对象状态或依赖内部状态一致性,设为private。

问题3: Button 的接口 const std::string& get_label() const; 返回 const std::string& 。简要说明以下两种接口设计在性能和安全性方面的差异。

接口1: const std::string& get_label() const;

接口2: const std::string get_label() const;

性能:接口1(返回const std::string&)更优,无需拷贝,无额外开销;接口2(返回const std::string)需拷贝对象,性能较低。

安全性:接口2更安全,返回副本避免悬空引用;接口1的引用依赖原对象生命周期,存在访问风险。

问题4:把代码中所有 xx.push_back(Button(xxx)) 改成 xx.emplace_back(xxx) ,观察程序是否正常运行;查阅资料,回答两种写法的差别。

程序可正常运行。差别如下:构造逻辑:push_back先构造临时对象再移动/拷贝到容器;emplace_back直接在容器内构造对象。

参数要求:push_back需传入已构造对象;emplace_back传入构造函数参数。

性能:emplace_back无临时对象开销,性能更优。

场景:push_back适用于复用现有对象;emplace_back适用于新建对象。

 

二、实验任务2

源代码task2

 1 #include <iostream>
 2 #include <vector>
 3 
 4 void test1();
 5 void test2();
 6 void output1(const std::vector<int> &v);
 7 void output2(const std::vector<int> &v);
 8 void output3(const std::vector<std::vector<int>>& v);
 9 
10 int main() {
11     std::cout << "深复制验证1: 标准库vector<int>\n";
12     test1();
13 
14     std::cout << "\n深复制验证2: 标准库vector<int>嵌套使用\n";
15     test2();
16 }
17 
18 void test1() {
19     std::vector<int> v1(5, 42);
20     const std::vector<int> v2(v1);
21 
22     std::cout << "**********拷贝构造后**********\n";
23     std::cout << "v1: "; output1(v1);
24     std::cout << "v2: "; output1(v2);
25     
26     v1.at(0) = -1;
27 
28     std::cout << "**********修改v1[0]后**********\n";
29     std::cout << "v1: "; output1(v1);
30     std::cout << "v2: "; output1(v2); 
31 }
32 
33 void test2() {
34     std::vector<std::vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}};
35     const std::vector<std::vector<int>> v2(v1);
36 
37     std::cout << "**********拷贝构造后**********\n";
38     std::cout << "v1: "; output3(v1);
39     std::cout << "v2: "; output3(v2);
40 
41     v1.at(0).push_back(-1);
42 
43     std::cout << "**********修改v1[0]后**********\n";
44     std::cout << "v1: \n";  output3(v1);
45     std::cout << "v2: \n";  output3(v2);
46 }
47 
48 // 使用xx.at()+循环输出vector<int>数据项
49 void output1(const std::vector<int> &v) {
50     if(v.size() == 0) {
51         std::cout << '\n';
52         return;
53     }
54     
55     std::cout << v.at(0);
56     for(auto i = 1; i < v.size(); ++i)
57         std::cout << ", " << v.at(i);
58     std::cout << '\n';  
59 }
60 
61 // 使用迭代器+循环输出vector<int>数据项
62 void output2(const std::vector<int> &v) {
63     if(v.size() == 0) {
64         std::cout << '\n';
65         return;
66     }
67     
68     auto it = v.begin();
69     std::cout << *it;
70 
71     for(it = v.begin()+1; it != v.end(); ++it)
72         std::cout << ", " << *it;
73     std::cout << '\n';
74 }
75 
76 // 使用auto for分行输出vector<vector<int>>数据项
77 void output3(const std::vector<std::vector<int>>& v) {
78     if(v.size() == 0) {
79         std::cout << '\n';
80         return;
81     }
82 
83     for(auto &i: v)
84         output2(i);
85 }
task2.cpp

运行结果截图

c6da9a65b39fd4db6697b236c424bba1

问题1:测试模块1中这两行代码分别完成了什么构造? v1、v2各包含多少个值为42的数据项?
构造类型:std::vector<int> v1(5, 42)调用填充构造函数(创建指定数量且元素值相同的vector);

const std::vector<int> v2(v1)调用拷贝构造函数(复制v1的所有内容)。

数据项数量:v1和v2均包含5个值为42的数据项。

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

结果:v1.size () = 2,v2.size () = 2,v1 [0].size () = 3。

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

能否等效:能实现同等效果(均修改v1第一个元素的值为-1)。

核心区别:at()会对索引进行边界检查(超出范围抛出异常),安全性更高但性能略低;

[ ] 运算符不做边界检查,性能更优但存在越界访问风险。

问题4:测试模块2中执行 v1.at(0).push_back(-1); 后

(1) 用以下两行代码,能否输出-1?为什么?

能输出-1。因为r是v1[0](vector类型元素)的引用,r.at(r.size()-1) 访问的是r的最后一个元素,而push_back(-1) 已将-1添加为r的最后一个元素。

(2)r定义成用 const & 类型接收返回值,在内存使用上有何优势?有何限制?

优势:避免对象拷贝,节省内存资源,无需额外创建副本。

限制:仅拥有只读权限,无法通过r修改所引用对象的内容(如调用push_back、修改元素值等)。

问题5:观察程序运行结果,反向分析、推断:

(1) 标准库模板类 vector 的复制构造函数实现的是深复制还是浅复制?

实现的是深复制(复制后两个vector的元素相互独立,修改一个不会影响另一个)。

(2) vector<T>::at() 接口思考: 当 v 是 vector<int> 时, v.at(0) 返回值类型是什么?当 v 是const vector<int> 时, v.at(0) 返回值类型又是什么?据此推断 at() 是否必须提供带const修饰的重载版本?

返回值类型:v为vector<int>时,返回int&;v为const vector<int>时,返回const int&。

重载必要性:必须提供const重载版本。因为const修饰的vector对象只能调用const成员函数,若没有const版本的at (),const vector将无法通过at ()安全访问元素。 

 

三、实验任务3

源代码task3

  1 #pragma once
  2 
  3 #include <iostream>
  4 
  5 // 动态int数组对象类
  6 class vectorInt{
  7 public:
  8     vectorInt();
  9     vectorInt(int n_);
 10     vectorInt(int n_, int value);
 11     vectorInt(const vectorInt &vi);
 12     ~vectorInt();
 13     
 14     int size() const;
 15     int& at(int index);
 16     const int& at(int index) const;
 17     vectorInt& assign(const vectorInt &vi);
 18 
 19     int* begin();
 20     int* end();
 21     const int* begin() const;
 22     const int* end() const;
 23 
 24 private:
 25     int n;     // 当前数据项个数
 26     int *ptr;  // 数据区
 27 };
 28 
 29 vectorInt::vectorInt():n{0}, ptr{nullptr} {
 30 }
 31 
 32 vectorInt::vectorInt(int n_): n{n_}, ptr{new int[n]} {
 33 }
 34 
 35 vectorInt::vectorInt(int n_, int value): n{n_}, ptr{new int[n_]} {
 36     for(auto i = 0; i < n; ++i)
 37         ptr[i] = value;
 38 }
 39 
 40 vectorInt::vectorInt(const vectorInt &vi): n{vi.n}, ptr{new int[n]} {
 41     for(auto i = 0; i < n; ++i)
 42         ptr[i] = vi.ptr[i];
 43 }
 44 
 45 vectorInt::~vectorInt() {
 46     delete [] ptr;
 47 }
 48 
 49 int vectorInt::size() const {
 50     return n;
 51 }
 52 
 53 const int& vectorInt::at(int index) const {
 54     if(index < 0 || index >= n) {
 55         std::cerr << "IndexError: index out of range\n";
 56         std::exit(1);
 57     }
 58 
 59     return ptr[index];
 60 }
 61 
 62 int& vectorInt::at(int index) {
 63     if(index < 0 || index >= n) {
 64         std::cerr << "IndexError: index out of range\n";
 65         std::exit(1);
 66     }
 67 
 68     return ptr[index];
 69 }
 70 
 71 vectorInt& vectorInt::assign(const vectorInt &vi) { 
 72     if(this == &vi) 
 73         return *this;
 74 
 75     int *ptr_tmp;
 76     ptr_tmp = new int[vi.n];
 77     for(int i = 0; i < vi.n; ++i)
 78         ptr_tmp[i] = vi.ptr[i];
 79     
 80     delete[] ptr;
 81     n = vi.n;
 82     ptr = ptr_tmp;
 83     return *this;
 84 }
 85 
 86 int* vectorInt::begin() {
 87     return ptr;
 88 }
 89 
 90 int* vectorInt::end() {
 91     return ptr+n;
 92 }
 93 
 94 const int* vectorInt::begin() const {
 95     return ptr;
 96 }
 97 
 98 const int* vectorInt::end() const {
 99     return ptr+n;
100 }
vectorInt.hpp
 1 #include "vectorInt.hpp"
 2 #include <iostream>
 3 
 4 void test1();
 5 void test2();
 6 void output1(const vectorInt &vi);
 7 void output2(const vectorInt &vi);
 8 
 9 int main() {
10     std::cout << "测试1: \n";
11     test1();
12 
13     std::cout << "\n测试2: \n";
14     test2();
15 }
16 
17 void test1() {
18     int n;
19     std::cout << "Enter n: ";
20     std::cin >> n;
21 
22     vectorInt x1(n);
23     for(auto i = 0; i < n; ++i)
24         x1.at(i) = (i+1)*10;
25     std::cout << "x1: ";  output1(x1);
26 
27     vectorInt x2(n, 42);
28     vectorInt x3(x2);
29     x2.at(0) = -1;
30     std::cout << "x2: ";  output1(x2);
31     std::cout << "x3: ";  output1(x3);
32 }
33 
34 void test2() {
35     const vectorInt  x(5, 42);
36     vectorInt y;
37 
38     y.assign(x);
39 
40     std::cout << "x: ";  output2(x);
41     std::cout << "y: ";  output2(y);
42 }
43 
44 // 使用xx.at()+循环输出vectorInt对象数据项
45 void output1(const vectorInt &vi) {
46     if(vi.size() == 0) {
47         std::cout << '\n';
48         return;
49     }
50         
51     std::cout << vi.at(0);
52     for(auto i = 1; i < vi.size(); ++i)
53         std::cout << ", " << vi.at(i);
54     std::cout << '\n';
55 }
56 
57 // 使用迭代器+循环输出vectorInt对象数据项
58 void output2(const vectorInt &vi) {
59     if(vi.size() == 0) {
60         std::cout << '\n';
61         return;
62     }
63     
64     auto it = vi.begin();
65     std::cout << *it;
66 
67     for(it = vi.begin()+1; it != vi.end(); ++it)
68         std::cout << ", " << *it;
69     std::cout << '\n';
70 }
task3.cpp

 运行结果截图

3ff7d9edd0e2ece4d9b72b96e0135399

问题1:当前验证性代码中, vectorInt 接口 assign 实现是安全版本。如果把 assign 实现改成版本2,逐条指出版本2存在的安全隐患和缺陷。(提示:对比两个版本,找出差异化代码,加以分析)

缺少自赋值检查:若自身赋值,会导致无效操作或数据异常;

内存分配顺序错误:先释放旧内存再分配新内存,若new分配失败抛出异常,原对象已失去有效内存,状态失效;

变量同步问题:分配新内存前修改了n,若后续操作异常,会导致n与ptr(旧内存地址)不匹配,对象状态混乱。

问题2:当前验证性代码中,重载接口 at 内部代码完全相同。若把非 const 版本改成如下实现,可消除重复并遵循“最小化接口”原则(未来如需更新接口,只更新const接口,另一个会同步)。

查阅资料,回答:

(1)static_cast<const vectorInt*>(this) 的作用是什么?转换前后 this 的类型分别是什么?转换目的?

作用:将非const成员函数中的this指针转换为const类型指针;

转换前后类型:转换前为vectorInt*,转换后为const vectorInt*;

转换目的:复用const版本at函数的代码,避免重复实现,遵循 “最小化接口” 原则。

(2)const_cast<int&> 的作用是什么?转换前后的返回类型分别是什么?转换目的?

作用:移除const限定,将const引用转换为非const引用;

转换前后返回类型:转换前为const int&,转换后为int&;

转换目的:让非const版本的at函数返回可修改的元素引用,满足非const对象修改元素的需求。

问题3: vectorInt 类封装了 begin() 和 end() 的const/非const接口。

(1)以下代码片段,分析编译器如何选择重载版本,并总结这两种重载分别适配什么使用场景

选择逻辑:非const对象(如v1)调用非const版本;const对象(如v2)或指向const对象的指针,只能调用const版本;

适配场景:非const版本适配需修改容器元素的场景;const版本适配仅读取元素、不修改的场景。

(2)拓展思考(选答*):标准库迭代器本质上是指针的封装。 vectorInt直接返回原始指针作为迭代器,这种设计让你对迭代器有什么新的理解?

vectorInt是连续存储容器,元素在内存中连续排列,其原始指针的移动逻辑与迭代器的遍历逻辑完全一致。由此可知,迭代器本质是对指针的封装,核心目的是统一不同容器的遍历接口,而底层可基于容器存储特性(如连续存储)直接复用指针功能。

问题4:以下两个构造函数及 assign 接口实现,都包含内存块的赋值/复制操作。使用算法库

能否改写:可以。

代码功能:std::fill_n(ptr, n, value):从指针ptr指向的起始位置,填充n个int类型元素,每个元素值均为value;

std::copy_n(v1.ptr, v1.n, ptr):从源指针v1.ptr开始,复制v1.n个元素到目标指针ptr指向的内存,内置类型直接复制字节,自定义类型调用拷贝构造函数;

std::copy_n(v1.ptr, v1.n, ptr_tmp):在assign接口中,先将v1.ptr指向的v1.n个元素复制到临时数组ptr_tmp,完成后再替换原对象的内存,避免自赋值导致的数据问题。

 

四、实验任务4

源代码task4

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <cstdlib>
 6 
 7 // 类Matrix声明
 8 class Matrix {
 9 public:
10     Matrix(int rows_, int cols_, double value = 0); // 构造rows_*cols_矩阵对象, 初值value
11     Matrix(int rows_, double value = 0);    // 构造rows_*rows_方阵对象, 初值value
12     Matrix(const Matrix &x);    // 深复制
13     ~Matrix();
14 
15     void set(const double *pvalue, int size);   // 按行复制pvalue指向的数据,要求size=rows*cols,否则报错退出
16     void clear();   // 矩阵对象数据项置0
17     
18     const double& at(int i, int j) const;   // 返回矩阵对象索引(i,j)对应的数据项const引用(越界则报错后退出)
19     double& at(int i, int j);   // 返回矩阵对象索引(i,j)对应的数据项引用(越界则报错后退出)
20     
21     int rows() const;   // 返回矩阵对象行数
22     int cols() const;   // 返回矩阵对象列数
23 
24     void print() const;   // 按行打印数据
25 
26 private:
27     int n_rows;      // 矩阵对象内元素行数
28     int n_cols;       // 矩阵对象内元素列数
29     double *ptr;    // 数据区
30 };
matrix.hpp
 1 #include "matrix.hpp"
 2 
 3 // 构造rows_行cols_列矩阵,元素初始值为value
 4 Matrix::Matrix(int rows_, int cols_, double value) 
 5     : n_rows(rows_), n_cols(cols_), ptr(nullptr) {
 6     if (rows_ <= 0 || cols_ <= 0) {
 7         std::cerr << "错误:矩阵的行数和列数必须是正整数!\n";
 8         std::exit(1);
 9     }
10     ptr = new double[rows_ * cols_];
11     std::fill_n(ptr, rows_ * cols_, value);
12 }
13 
14 // 构造rows_阶方阵,复用矩阵构造函数
15 Matrix::Matrix(int rows_, double value) 
16     : Matrix(rows_, rows_, value) {}
17 
18 // 深复制构造函数:独立分配内存并拷贝数据
19 Matrix::Matrix(const Matrix &x) 
20     : n_rows(x.n_rows), n_cols(x.n_cols), ptr(nullptr) {
21     ptr = new double[x.n_rows * x.n_cols];
22     std::copy_n(x.ptr, x.n_rows * x.n_cols, ptr);
23 }
24 
25 // 析构函数:释放内存,避免泄漏
26 Matrix::~Matrix() {
27     delete[] ptr;
28     ptr = nullptr;
29 }
30 
31 // 按行复制外部数据到矩阵
32 void Matrix::set(const double *pvalue, int size) {
33     if (size != n_rows * n_cols) {
34         std::cerr << "错误:输入数据大小 " << size << " 和矩阵大小 " 
35                   << n_rows * n_cols << " 不匹配!\n";
36         std::exit(1);
37     }
38     if (pvalue == nullptr) {
39         std::cerr << "错误:输入数据指针为空!\n";
40         std::exit(1);
41     }
42     std::copy_n(pvalue, size, ptr);
43 }
44 
45 // 矩阵所有元素置0
46 void Matrix::clear() {
47     std::fill_n(ptr, n_rows * n_cols, 0.0);
48 }
49 
50 // const版本at:返回不可修改的元素引用,越界报错
51 const double& Matrix::at(int i, int j) const {
52     if (i < 0 || i >= n_rows || j < 0 || j >= n_cols) {
53         std::cerr << "错误:索引 (" << i << ", " << j << ") 越界!"
54                   << "矩阵大小为 " << n_rows << "" << n_cols << "列\n";
55         std::exit(1);
56     }
57     return ptr[i * n_cols + j];
58 }
59 
60 // 非const版本at:返回可修改的元素引用,复用const版本逻辑
61 double& Matrix::at(int i, int j) {
62     return const_cast<double&>(static_cast<const Matrix*>(this)->at(i, j));
63 }
64 
65 // 返回行数
66 int Matrix::rows() const {
67     return n_rows;
68 }
69 
70 // 返回列数
71 int Matrix::cols() const {
72     return n_cols;
73 }
74 
75 // 按行打印矩阵,格式整洁
76 void Matrix::print() const {
77     for (int i = 0; i < n_rows; ++i) {
78         for (int j = 0; j < n_cols; ++j) {
79             if (j == 0) {
80                 std::cout << at(i, j);
81             } else {
82                 std::cout << ", " << at(i, j);
83             }
84         }
85         std::cout << "\n";
86     }
87 }
matrix.cpp
 1 #include <iostream>
 2 #include <cstdlib>
 3 #include "matrix.hpp"
 4 
 5 void test1();
 6 void test2();
 7 void output(const Matrix &m, int row_index);
 8 
 9 int main() {
10     std::cout << "测试1: \n";
11     test1();
12 
13     std::cout << "\n测试2: \n";
14     test2();
15 }
16 
17 void test1() {
18     double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
19 
20     int n, m;
21     std::cout << "Enter n and m: ";
22     std::cin >> n >> m;
23 
24     Matrix m1(n, m);    // 创建矩阵对象m1, 大小n×m
25     m1.set(x, n*m);     // 用一维数组x的值按行为矩阵m1赋值
26 
27     Matrix m2(m, n);    // 创建矩阵对象m2, 大小m×n
28     m2.set(x, m*n);     // 用一维数组x的值按行为矩阵m1赋值
29 
30     Matrix m3(n);       // 创建一个n×n方阵对象
31     m3.set(x, n*n);     // 用一维数组x的值按行为矩阵m3赋值
32 
33     std::cout << "矩阵对象m1: \n";   m1.print();
34     std::cout << "矩阵对象m2: \n";   m2.print();
35     std::cout << "矩阵对象m3: \n";   m3.print();
36 }
37 
38 void test2() {
39     Matrix m1(2, 3, -1);
40     const Matrix m2(m1);
41     
42     std::cout << "矩阵对象m1: \n";   m1.print();
43     std::cout << "矩阵对象m2: \n";   m2.print();
44 
45     m1.clear();
46     m1.at(0, 0) = 1;
47 
48     std::cout << "m1更新后: \n";
49     std::cout << "矩阵对象m1第0行 "; output(m1, 0);
50     std::cout << "矩阵对象m2第0行: "; output(m2, 0);
51 }
52 
53 // 输出矩阵对象row_index行所有元素
54 void output(const Matrix &m, int row_index) {
55     if(row_index < 0 || row_index >= m.rows()) {
56         std::cerr << "IndexError: row index out of range\n";
57         exit(1);
58     }
59 
60     std::cout << m.at(row_index, 0);
61     for(int j = 1; j < m.cols(); ++j)
62         std::cout << ", " << m.at(row_index, j);
63     std::cout << '\n';
64 }
task4.cpp

运行结果截图

2fa876006aefe76e38fa719741a93f88

 

五、实验任务5

源代码task5

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <string>
 5 
 6 // 联系人类
 7 class Contact {
 8 public:
 9     Contact(const std::string &name_, const std::string &phone_);
10 
11     const std::string &get_name() const;
12     const std::string &get_phone() const;
13     void display() const;
14 
15 private:
16    std::string name;    // 必填项
17    std::string phone;   // 必填项
18 };
19 
20 Contact::Contact(const std::string &name_, const std::string &phone_):name{name_}, phone{phone_} {
21 }
22 
23 const std::string& Contact::get_name() const {
24     return name;
25 }
26 
27 const std::string& Contact::get_phone() const {
28     return phone;
29 }
30 
31 void Contact::display() const {
32     std::cout << name << ", " << phone;
33 }
contact.hpp
 1 # pragma  once
 2 
 3 #include <iostream>
 4 #include <string>
 5 #include <vector>
 6 #include <algorithm>
 7 #include "contact.hpp"
 8 
 9 // 通讯录类
10 class ContactBook {
11 public:
12     void add(const std::string &name, const std::string &phone); // 添加联系人
13     void remove(const std::string &name); // 移除联系人
14     void find(const std::string &name) const; // 查找联系人
15     void display() const; // 显示所有联系人
16     size_t size() const;
17     
18 private:
19     int index(const std::string &name) const;  // 返回联系人在contacts内索引,如不存在,返回-1
20     void sort(); // 按姓名字典序升序排序通讯录
21 
22 private:
23     std::vector<Contact> contacts;
24 };
25 
26 void ContactBook::add(const std::string &name, const std::string &phone) {
27     if(index(name) == -1) {
28         contacts.push_back(Contact(name, phone));
29         std::cout << name << " add successfully.\n";
30         sort();
31         return;
32     }
33 
34     std::cout << name << " already exists. fail to add!\n"; 
35 }
36 
37 void ContactBook::remove(const std::string &name) {
38     int i = index(name);
39 
40     if(i == -1) {
41         std::cout << name << " not found, fail to remove!\n";
42         return;
43     }
44 
45     contacts.erase(contacts.begin()+i);
46     std::cout << name << " remove successfully.\n";
47 }
48 
49 void ContactBook::find(const std::string &name) const {
50     int i = index(name);
51 
52     if(i == -1) {
53         std::cout << name << " not found!\n";
54         return;
55     }
56 
57     contacts[i].display(); 
58     std::cout << '\n';
59 }
60 
61 void ContactBook::display() const {
62     for(auto &c: contacts) {
63         c.display(); 
64         std::cout << '\n';
65     }
66 }
67 
68 size_t ContactBook::size() const {
69     return contacts.size();
70 }
71 
72 // 待补足1:int index(const std::string &name) const;实现
73 // 返回联系人在contacts内索引; 如不存在,返回-1
74 int ContactBook::index(const std::string &name) const {
75     for (size_t i = 0; i < contacts.size(); ++i) {
76         // 比较联系人姓名与目标姓名,完全匹配则返回当前索引
77         if (contacts[i].get_name() == name) {
78             return static_cast<int>(i);
79         }
80     }
81     // 遍历结束未找到,返回-1
82     return -1;
83 }
84 
85 // 待补足2:void ContactBook::sort();实现
86 // 按姓名字典序升序排序通讯录
87 void ContactBook::sort() {
88     // 使用std::sort,自定义比较规则:按姓名升序
89     std::sort(contacts.begin(), contacts.end(), 
90         [](const Contact& a, const Contact& b) {
91             return a.get_name() < b.get_name(); // 字符串字典序比较
92         });
93 }
contactBook.hpp
 1 #include "contactBook.hpp"
 2 
 3 void test() {
 4     ContactBook contactbook;
 5 
 6     std::cout << "1. add contacts\n";
 7     contactbook.add("Bob", "18199357253");
 8     contactbook.add("Alice", "17300886371");
 9     contactbook.add("Linda", "18184538072");
10     contactbook.add("Alice", "17300886371");
11 
12     std::cout << "\n2. display contacts\n";
13     std::cout << "There are " << contactbook.size() << " contacts.\n";
14     contactbook.display();
15 
16     std::cout << "\n3. find contacts\n";
17     contactbook.find("Bob");
18     contactbook.find("David");
19 
20     std::cout << "\n4. remove contact\n";
21     contactbook.remove("Bob");
22     contactbook.remove("David");
23 }
24 
25 int main() {
26     test();
27 }
task5.cpp

运行结果截图

dcb36fc2bcf3870c4ded1e3d8b022074

 

实验总结

本次实验结合C++标准库std::vector与std::sort,搭配类的组合设计,简洁实现了通讯录增删查显功能。标准库的复用既减少了代码量,又提升了安全性,让我感受到其便捷性。同时也意识到,大小写区分、索引转换等细节不容忽视,后续编程需更注重严谨性。

posted @ 2025-11-20 00:00  htsjubbymjeymsy  阅读(11)  评论(1)    收藏  举报