实验3

任务1

代码:

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

截图:

屏幕截图 2026-11-26 171130

 问题1:

是。成员button是值语义存储Button对象,而Button对象生命周期完全由WIndow管理。

问题2:

优点:可以直接查询窗口内是否存在某按钮,不用自己遍历。​

风险:可能会基于该函数错误编写业务,破坏类封装。

public :是类对外提供服务接口,用户需要调用才能完成业务,不属于内部实现细节。

private :仅类内部成员函数调用、属于内部实现细节;对外不需要,暴露后容易被误用,可能破坏对象内部状态,就放到private。

问题3:

接口1:

const std::string& get_label() const; 

性能:返回常量引用,不产生字符串拷贝,性能高。

安全:返回const引用,外部不能修改内部 label_ ,保证内部状态安全。

接口2:

std::string get_label() const; 

性能:返回值,会调用string拷贝构造,产生副本,存在拷贝开销。

安全:返回副本,外部修改副本不会影响对象内部数据,安全性同样高,但是性能代价更大。

问题4:

①  可以正常运行。

 push_back(Button(xxx)) :先在外部构造临时Button对象,再将临时对象移动/拷贝到vector容器。

 emplace_back(xxx) :直接在vector容器内存空间原地构造Button对象,不需要生成临时对象。

② 可以

std::any_of()是对范围内的元素进行判断,若有满足条件的元素立即返回true/false,并且终止比较。它的参数是(范围起点, 范围终点, 判断条件),返回值为true/false。

③ 可以

参数:迭代器区间 [first,last) ,谓词pred​

功能:查找区间第一个满足谓词条件的元素;找到返回该元素迭代器;找不到返回 last 尾后迭代器。

任务2

代码:

 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     std::cout << "\n深复制验证2: 标准库vector<int>嵌套使用\n";
14     test2();
15     return 0;
16 }
17 
18 void test1() {
19     std::vector<int> v1(5, 42);
20     const std::vector<int> v2(v1);
21     std::cout << "**********拷贝构造后**********\n";
22     std::cout << "v1: "; output1(v1);
23     std::cout << "v2: "; output1(v2);
24 
25     v1[0] = -1;
26     std::cout << "**********修改v1[0]后**********\n";
27     std::cout << "v1: "; output1(v1);
28     std::cout << "v2: "; output1(v2);
29 }
30 
31 void test2() {
32     std::vector<std::vector<int>> v1{{1, 2, 3}, {4, 5, 6, 7}};
33     const std::vector<std::vector<int>> v2(v1);
34 
35     std::cout << "**********拷贝构造后**********\n";
36     std::cout << "v1:\n"; output3(v1);
37     std::cout << "v2:\n"; output3(v2);
38 
39     v1[0].push_back(-1);
40     std::cout << "**********修改v1[0]后**********\n";
41     std::cout << "v1:\n"; output3(v1);
42     std::cout << "v2:\n"; output3(v2);
43 }
44 
45 void output1(const std::vector<int> &v) {
46     if(v.size() == 0) {
47         std::cout << '\n';
48         return;
49     }
50     std::cout << v[0];
51     for(auto i = 1; i < v.size(); ++i)
52         std::cout << ", " << v[i];
53     std::cout << '\n';
54 }
55 
56 void output2(const std::vector<int> &v) {
57     if(v.size() == 0) {
58         std::cout << '\n';
59         return;
60     }
61     auto it = v.begin();
62     std::cout << *it;
63     for(it = v.begin()+1; it != v.end(); ++it)
64         std::cout << ", " << *it;
65     std::cout << '\n';
66 }
67 
68 void output3(const std::vector<std::vector<int>>& v) {
69     if(v.size() == 0) {
70         std::cout << '\n';
71         return;
72     }
73     for(auto &i: v)
74         output2(i);
75 }
task2.cpp

截图:

屏幕截图 2026-11-26 180849

 问题1:

std::vector<int> v1(5,42); :构造函数,创建v1,5个元素全部初始化为42。v1有5个42。

const std::vector<int> v2(v1); :拷贝构造函数,用v1复制生成v2。v2有5个42。

问题2:
 v1.size() = 2 ; v2.size() = 2 ; v1[0].size() = 3 。

问题3:

能。

区别:

1:不做越界检查;索引越界,未定义行为。

2 :做下标越界检查;下标越界抛出 std::out_of_range 异常。

问题4:

① 可以输出-1。 v1[0] 返回内部vector引用; const std::vector<int>& r 绑定这个对象;修改v1[0]后r仍是该对象别名,访问末尾元素得到‑1。

②  const & 优势:不拷贝容器,直接绑定原对象,节省内存,避免拷贝开销。

限制:r是const引用,不能通过r修改容器内元素。

问题5:

1. 深拷贝

2. 普通 vector<int> v , v.at(0) 返回 int& ;

const vector<int> v , v.at(0) 返回 const int& 。

必须提供const重载版本。

任务3

代码:

 1 #pragma once
 2 #include <iostream>
 3 #include <stdexcept>
 4 
 5 class vectorInt{
 6 public:
 7     vectorInt();
 8     vectorInt(int n);
 9     vectorInt(int n, int value);
10     vectorInt(const vectorInt &vi);
11     ~vectorInt();
12 
13     int size() const;
14     int& at(int index);
15     const int& at(int index) const;
16     vectorInt& assign(const vectorInt &vi);
17 
18     int* begin();
19     int* end();
20     const int* begin() const;
21     const int* end() const;
22 
23 private:
24     int n_;
25     int *pdata_;
26 };
27 
28 inline vectorInt::vectorInt():n_{0}, pdata_{nullptr} {
29 }
30 
31 inline vectorInt::vectorInt(int n): n_{n}, pdata_{new int[n]} {
32 }
33 
34 inline vectorInt::vectorInt(int n, int value): n_{n}, pdata_{new int[n]} {
35     for(auto i = 0; i < n_; ++i)
36         pdata_[i] = value;
37 }
38 
39 inline vectorInt::vectorInt(const vectorInt &vi): n_{vi.n_}, pdata_{new int[n_]} {
40     for(auto i = 0; i < n_; ++i)
41         pdata_[i] = vi.pdata_[i];
42 }
43 
44 inline vectorInt::~vectorInt() {
45     delete [] pdata_;
46 }
47 
48 inline int vectorInt::size() const {
49     return n_;
50 }
51 
52 inline const int& vectorInt::at(int index) const {
53     if(index < 0 || index >= n_)
54         throw std::out_of_range("vectorInt::at: index out of range");
55     return pdata_[index];
56 }
57 
58 inline int& vectorInt::at(int index) {
59     if(index < 0 || index >= n_)
60         throw std::out_of_range("vectorInt::at: index out of range");
61     return pdata_[index];
62 }
63 
64 inline vectorInt& vectorInt::assign(const vectorInt &vi) {
65     if(this == &vi)
66         return *this;
67     int *ptr;
68     ptr = new int[vi.n_];
69     for(int i = 0; i < vi.n_; ++i)
70         ptr[i] = vi.pdata_[i];
71     delete[] pdata_;
72     n_ = vi.n_;
73     pdata_ = ptr;
74     return *this;
75 }
76 
77 inline int* vectorInt::begin() {
78     return pdata_;
79 }
80 
81 inline int* vectorInt::end() {
82     return pdata_ + n_;
83 }
84 
85 inline const int* vectorInt::begin() const {
86     return pdata_;
87 }
88 
89 inline const int* vectorInt::end() const {
90     return pdata_ + n_;
91 }
vectorInt.hpp
 1 #include "vectorInt.hpp"
 2 #include <iostream>
 3 
 4 void test1();
 5 void test2();
 6 void test3();
 7 void output1(const vectorInt &vi);
 8 void output2(const vectorInt &vi);
 9 
10 int main() {
11     std::cout << "测试1: 构造、更新\n";
12     test1();
13     std::cout << "\n测试2: const对象、赋值\n";
14     test2();
15     std::cout << "\n测试3: 赋值\n";
16     test3();
17     return 0;
18 }
19 
20 void test1() {
21     int n;
22     std::cout << "Enter n: ";
23     std::cin >> n;
24     vectorInt x1(n);
25     for(auto i = 0; i < n; ++i)
26         x1.at(i) = (i+1)*10;
27     std::cout << "x1: "; output1(x1);
28 
29     vectorInt x2(n, 42);
30     vectorInt x3(x2);
31     x2.at(0) = -1;
32     std::cout << "x2: "; output1(x2);
33     std::cout << "x3: "; output1(x3);
34 }
35 
36 void test2() {
37     const vectorInt x(5, 42);
38     vectorInt y;
39     y.assign(x);
40     std::cout << "x: "; output2(x);
41     std::cout << "y: "; output2(y);
42     y.at(0) = -1;
43     std::cout << "x: "; output2(x);
44     std::cout << "y: "; output2(y);
45 }
46 
47 void test3() {
48     vectorInt x(5, 42);
49     std::cout << "x: "; output2(x);
50     x.assign(x);
51     std::cout << "x: "; output2(x);
52 }
53 
54 void output1(const vectorInt &vi) {
55     if(vi.size() == 0) {
56         std::cout << '\n';
57         return;
58     }
59     std::cout << vi.at(0);
60     for(auto i = 1; i < vi.size(); ++i)
61         std::cout << ", " << vi.at(i);
62     std::cout << '\n';
63 }
64 
65 void output2(const vectorInt &vi) {
66     if(vi.size() == 0) {
67         std::cout << '\n';
68         return;
69     }
70     auto it = vi.begin();
71     std::cout << *it;
72     for(it = vi.begin()+1; it != vi.end(); ++it)
73         std::cout << ", " << *it;
74     std::cout << '\n';
75 }
task3.cpp

截图:

屏幕截图 2026-11-26 182047

 问题1:

屏幕截图 2026-11-26 182357

无异常

缺陷:缺少自赋值判断 if(this == &vi) return *this; 。

安全隐患:循环读取野指针内存,发生未定义行为,程序应该会崩溃。

问题2:

1.作用:把当前对象指针转换成const对象指针,调用const版本at()成员函数。

转换前: this 类型  vectorInt* (普通对象指针)​

转换后: const vectorInt* 

2.作用:剥离const属性,返回可修改引用给非const的at()

转换前返回: const int&​

转换后返回: int&

问题3:

auto it1 = v1.begin(); :v1是非const对象,调用非const  int* begin() ;

auto it2 = v2.begin(); :v2是const对象,调用const版本 const int* begin() const 。

问题4:

可行

更新1:std::fill_n(pdata_, n_, value); :从pdata_起始,n_个元素全部填充value。替代循环赋值。​

更新2:std::copy_n(vi.pdata_, vi.n_, pdata_); :从vi.pdata_拷贝n_个int,复制到pdata_指向内存,替代for循环拷贝。​

更新3:std::copy_n(vi.pdata_, vi.n_, ptr); :把vi的数据拷贝到新分配ptr缓冲区。

任务4

代码:

 1 #pragma once
 2 class Matrix {
 3 public:
 4     Matrix(int n_rows, int n_cols, double value = 0);
 5     Matrix(int n_rows, double value = 0);
 6     Matrix(const Matrix &x);
 7 
 8     ~Matrix();
 9     void set(const double *pvalue, int size);
10     void clear();
11 
12     const double& at(int i, int j) const;
13     double& at(int i, int j);
14 
15     int rows() const;
16     int cols() const;
17 
18     void print() const ;
19 private:
20     int n_rows_;
21     int n_cols_;
22     double *pdata_;
23 };
matrix.h
 1 #include "matrix.h"
 2 #include <algorithm>
 3 #include <iostream>
 4 #include <stdexcept>
 5 
 6 Matrix::Matrix(int n_rows, int n_cols, double value)
 7 : n_rows_{n_rows}, n_cols_{n_cols}, pdata_{new double[n_rows*n_cols]} {
 8     std::fill_n(pdata_, n_rows*n_cols, value);
 9 }
10 
11 Matrix::Matrix(int n_rows, double value): Matrix(n_rows, n_rows, value) {
12 }
13 
14 Matrix::Matrix(const Matrix &x) {
15     n_rows_ = x.n_rows_;
16     n_cols_ = x.n_cols_;
17     pdata_ = new double[n_rows_ * n_cols_];
18     std::copy_n(x.pdata_, n_rows_ * n_cols_, pdata_);
19 }
20 
21 Matrix::~Matrix() {
22     delete[] pdata_;
23 }
24 
25 void Matrix::set(const double *pvalue, int size) {
26     if(size != n_rows_ * n_cols_)
27         throw std::invalid_argument("size must match");
28     std::copy_n(pvalue, size, pdata_);
29 }
30 
31 void Matrix::clear() {
32     std::fill_n(pdata_, n_rows_ * n_cols_, 0);
33 }
34 
35 const double& Matrix::at(int i, int j) const {
36     if(i < 0 || i >= n_rows_ || j < 0 || j >= n_cols_)
37         throw std::out_of_range("i must be [0, n_rows_ - 1] and j must be [0, n_cols_ - 1]");
38     return pdata_[i * n_cols_ + j];
39 }
40 
41 double& Matrix::at(int i, int j) {
42     return const_cast<double&>(static_cast<const Matrix*>(this)->at(i,j));
43 }
44 
45 int Matrix::rows() const {
46     return n_rows_;
47 }
48 
49 int Matrix::cols() const {
50     return n_cols_;
51 }
52 
53 void Matrix::print() const {
54     for(int i = 0; i < n_rows_; ++i) {
55         for(int j = 0; j < n_cols_; ++j) {
56             if(j>0) std::cout << ", ";
57             std::cout << at(i,j);
58         }
59         std::cout << "\n";
60     }
61 }
matrix.cpp
 1 #include <cstdlib>
 2 #include <iostream>
 3 #include <stdexcept>
 4 #include "matrix.h"
 5 
 6 void test1();
 7 void test2();
 8 void output(const Matrix &m, int row_index);
 9 
10 int main() {
11     std::cout << "测试1: \n";
12     test1();
13     std::cout << "\n测试2: \n";
14     test2();
15     return 0;
16 }
17 
18 void test1() {
19     double x[1000] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
20     int n, m;
21     std::cout << "Enter n and m: ";
22     std::cin >> n >> m;
23     Matrix m1(n, m);
24     m1.set(x, n*m);
25     Matrix m2(m, n);
26     m2.set(x, m*n);
27     Matrix m3(n);
28     m3.set(x, n*n);
29     std::cout << "矩阵m1: \n"; m1.print();
30     std::cout << "矩阵m2: \n"; m2.print();
31     std::cout << "矩阵m3: \n"; m3.print();
32 }
33 
34 void test2() {
35     Matrix m1(2, 5, -1);
36     const Matrix m2(m1);
37     std::cout << "矩阵m1: \n"; m1.print();
38     std::cout << "矩阵m2: \n"; m2.print();
39     m1.clear();
40     m1.at(0, 0) = 1;
41     m1.at(0, 1) = 2;
42     std::cout << "m1更新后: \n";
43     std::cout << "矩阵m1第0行 "; output(m1, 0);
44     std::cout << "矩阵m2第0行: "; output(m2, 0);
45 }
46 
47 void output(const Matrix &m, int row_index) {
48     if(row_index < 0 || row_index >= m.rows())
49         throw std::out_of_range("row_index must in [0, m.rows()-1]");
50     std::cout << m.at(row_index, 0);
51     for(int j = 1; j < m.cols(); ++j)
52         std::cout << ", " << m.at(row_index, j);
53     std::cout << '\n';
54 }
task4.cpp

截图:

屏幕截图 2026-11-26 183551

 任务5

代码:

 1 #pragma once
 2 #include <iostream>
 3 #include <string>
 4 
 5 class Contact {
 6 public:
 7     Contact(const std::string &name, const std::string &phone);
 8     const std::string &get_name() const;
 9     const std::string &get_phone() const;
10     void display() const;
11 
12 private:
13     std::string name_;
14     std::string phone_;
15 };
16 
17 inline Contact::Contact(const std::string &name, const std::string &phone):name_{name}, phone_{phone} {
18 }
19 
20 inline const std::string& Contact::get_name() const {
21     return name_;
22 }
23 
24 inline const std::string& Contact::get_phone() const {
25     return phone_;
26 }
27 
28 inline void Contact::display() const {
29     std::cout << name_ << "," << phone_;
30 }
contact.hpp
 1 #pragma once
 2 #include "contact.hpp"
 3 #include <algorithm>
 4 #include <iostream>
 5 #include <string>
 6 #include <vector>
 7 
 8 class ContactBook {
 9 public:
10     void add(const std::string &name, const std::string &phone);
11     void remove(const std::string &name);
12     void find(const std::string &name) const;
13     void display() const;
14     size_t size() const;
15 
16 private:
17     int index(const std::string &name) const;
18     void sort();
19 
20 private:
21     std::vector<Contact> contacts_;
22 };
23 
24 inline void ContactBook::add(const std::string &name, const std::string &phone) {
25     if(index(name) == -1) {
26         contacts_.push_back(Contact(name, phone));
27         std::cout << name << " add successfully.\n";
28         sort();
29         return;
30     }
31     std::cout << name << " already exists.fail to add!\n";
32 }
33 
34 inline void ContactBook::remove(const std::string &name) {
35     int i = index(name);
36     if(i == -1) {
37         std::cout << name << " not found,fail to remove!\n";
38         return;
39     }
40     contacts_.erase(contacts_.begin()+i);
41     std::cout << name << " remove successfully.\n";
42 }
43 
44 inline void ContactBook::find(const std::string &name) const {
45     int i = index(name);
46     if(i == -1) {
47         std::cout << name << " not found!\n";
48         return;
49     }
50     contacts_[i].display();
51     std::cout << '\n';
52 }
53 
54 inline void ContactBook::display() const {
55     for(auto &c: contacts_) {
56         c.display();
57         std::cout << '\n';
58     }
59 }
60 
61 inline size_t ContactBook::size() const {
62     return contacts_.size();
63 }
64 
65 //=====补全index=====
66 inline int ContactBook::index(const std::string &name) const{
67     for(int i=0;i<contacts_.size();i++){
68         if(contacts_[i].get_name() == name){
69             return i;
70         }
71     }
72     return -1;
73 }
74 
75 //====补全sort,字典序升序====
76 inline void ContactBook::sort(){
77     std::sort(contacts_.begin(),contacts_.end(),
78         [](const Contact& a,const Contact& b){
79             return a.get_name() < b.get_name();
80         });
81 }
contactbook.hpp
 1 #include "contactbook.hpp"
 2 
 3 void test() {
 4     ContactBook contactbook;
 5     std::cout << "1.add contacts\n";
 6     contactbook.add("Bob", "18199357253");
 7     contactbook.add("Alice", "17300886371");
 8     contactbook.add("Linda", "18184538072");
 9     contactbook.add("Alice", "17300886371");
10 
11     std::cout << "\n2.display contacts\n";
12     std::cout << "There are " << contactbook.size() << " contacts.\n";
13     contactbook.display();
14 
15     std::cout << "\n3.find contacts\n";
16     contactbook.find("Bob");
17     contactbook.find("David");
18 
19     std::cout << "\n4. remove contact\n";
20     contactbook.remove("Bob");
21     contactbook.remove("David");
22 
23     std::cout << "\n5.display contacts\n";
24     std::cout << "There are " << contactbook.size() << " contacts.\n";
25     contactbook.display();
26 }
27 
28 int main() {
29     test();
30     return 0;
31 }
task5.cpp

截图:

屏幕截图 2026-11-26 184049

posted @ 2026-11-26 18:42  亓炅  阅读(3)  评论(0)    收藏  举报