实验3
实验任务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;
}
运行截图

问题1
是组合关系,Buttons对象是以值的形式存储的。生命周期管理方面,当Window对象销毁时,butttons_也会被自动销毁,从而使vector里面所有Button对象的析构函数被调用,体现了组合关系共存亡,共生死的特点
问题2
(1)优点是外部可以直接访问,看某个按钮是否存在,风险是:由于改成了public,暴露了内部实现细节,削弱封装性,一旦公开,外部代码就可能依赖它,以后想修改查找规则的时候,需要考虑是否会影响客户。
(2)如果用户需要自己去执行这项功能,那么通常选择public,如果以后改变内部实现细节的时候,用户根本就不需要知道的话,那么就应该选择private,公开之后有可能会破坏对象状态,因为外部可能可以随意删除添加修改按钮,这样的风险就比较高了
问题3
接口1:直接返回的是内部成员的引用,没有拷贝所带来的开销,适合频繁调用的只读场景;接口2:每次调用都会拷贝构造一个新的对象,会带来内存分配的开销,但是由于它返回的是一个独立的副本,所以外部对这个副本的操作与原始的Button对象完全脱钩,不需要担心生命周期问题,接口1与之相反,如果Button对象被销毁,那么该引用就会失效,再访问它就会导致未定义行为,比较危险
问题4
(1)仍能正常运行,运行结果也没什么不同。push_back是先构造一个临时的Button对象,再将其移动或者拷贝进vecotr里面,而emplace_back则是直接就地调用Button的构造函数,将括号里面的参数直接传到vector内部。
(2)可以,std::any_of功能是查看给定范围内是否至少有一个元素满足所给的判定条件,前两个参数是迭代器范围从第一个参数开始到第二个参数结束,左闭右开,[&](const Button &b) { return b.get_label() == label; }意思是捕获外部变量label,判断当前的得到的按钮label是否与目标相等。,返回bool,如果范围为空返回false,如果有的话就返回true,没有的话就返回false
(3)find_if也是遍历范围,范围同上,然后找到第一个满足条件的元素并返回迭代器,如果没有找到,就返回last最后一个,这里即为buttons_.end(),也就是结束迭代器,
实验任务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);
}
运行截图

问题1
第一行调用了vector的带参构造函数,初始化v1,分配了5个元素的内存空间,并把每一个元素初始化为42;第二行调用了vector的拷贝构造函数,使用已存在的v1来初始化v2,v2是v1的深拷贝,也是包含了5个值为42的数据项
问题2
v1.size()=2
v2.size()=2
v1[0].size()=3
问题3
能。区别:v1.at(0)会进行边界检查,如果越界会抛出异常,因此更加安全。另一个则不会。
问题4
(1)能输出-1,r作为引用绑定的是{1,2,3},在v1[0].push_back(-1)之后v1[0]就变成了{1,2,3,-1},然后要输出的r[r.size()-1]中r.size()-1指向的就是最后一个元素,所以输出的就是{1,2,3,-1}的最后一个元素-1
(2)避免了深拷贝,因为如果是std::vector
问题5
(1)深拷贝
(2)类型是int&;类型是const int&;所以必须是提供带const修饰的
重载版本
实验任务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(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 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;
//}
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';
}
运行截图

问题1
版本2运行截图
delete[] pdata_;如果执行x.assign(x);this指针和&vi指向的是同一个对象,所以this->pdata_和vi.pdata_指向的是同一块内存,执行delete之后,这块内存就被释放,成了野指针,但是vi.pdata_依旧指向这块区域,之后执行pdata_=new int[n_]申请新内存,this->pdata_指向新内存,而vi.pdata_还是野指针,后面的for循环会导致非法访问,导致程序崩溃。
奇怪的是我自己运行的时候程序没有报错,还是正常输出,我询问ai之后它告诉我这应该是侥幸运行,delete[]释放内存后操作系统并未立刻将那块内存清零,且紧接着 new 分配的内存没有与原先那块被释放的内存发生重叠覆盖。因此程序读到了残留在原内存上的42数据。如果换一个编译器、操作系统环境,或者内存分配器,这段代码极大概率会触发段错误(Segment Fault)导致程序崩溃。
问题2
将非const的this指针转换成const的指针,转换前是vectorInt指向非const对象,转换后是const vectorInt,目的是为了在转换后的指针调用at(index)时,强制其匹配到const版本的at(),因为const版本里有越界检查(throw),这样非const版本的at只需要写一行代码,不用吧if(index<0||index>=n)写两遍
(2)作用是去除了const属性,转换前是const int&类型,转换后是int&类型,目的是去掉const之后这样外界就可以修改元素,后续操作更安全
问题3
v1.begin()会调用非const版本的,因为v1是普通对象,编译器优先匹配非const成员函数,v2.begin()会调用const版本的,因为v2是const对象,只能调用const成员函数;非const适用于需要修改内部元素的场景,const适用于仅需要读取内部元素,要保证数据不被修改的场景
问题4
·可以,从pdata_开始,长度为n_都用value来填充元素
·可以,从指针vi.pdata_开始,拷贝vi.n_个元素到目标指针pdata_开始的连续内存中
·可以,功能同上将数据拷贝到ptr内存中
实验任务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)
:n_rows_{ x.n_rows_ }, n_cols_{ x.n_cols_ }, pdata_{ new double[x.n_rows_ * x.n_cols_] } {
std::copy_n(x.pdata_,n_rows_* n_cols_,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);
}
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 << (j == 0 ? "" : ",") << 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.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';
}
运行截图


问题
会越界访问,比如说输入2 3,改完之后double x[5]只有5个元素,但是set函数会强行读取size=rows*cols=6个元素,于是就会发生数组越界读取,m1最后一个数据就是随机的一个脏数据,比如说这样
ai告诉我改进方法有一种是使用std::initializer_list,直接传入初始化列表,编译器会推导出确切的大小:
void set(std::initializer_list<double> values);
或者这么写
template<size_t N>
void set(const double (&pvalue)[N] {
if(N!=static_cast<size_t>(n_rows_*n_cols_)) {
throw std::invalid_argument("array size must match matric size");
}
std::copy_n(pvalue,N,pdata_);
}
输入2 3之后,编译器根据数组推导出N=5,代码里面N都被5替换,由于发现5!=static_cast<size_t>(2*3)即5!=6,所以程序执行throw语句
实验任务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();
}
// 待补足1:int index(const std::string &name) const;实现
// 返回联系人在contacts内索引; 如不存在,返回-1
inline int ContactBook::index(const std::string& name) const {
auto it = find_if(contacts_.begin(), contacts_.end(),
[&](const Contact& c) { return c.get_name() == name;
});
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() {
std::sort(contacts_.begin(), contacts_.end(),
[](const Contact& a, const Contact& b) {
return a.get_name() < b.get_name();
});
}
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();
}
运行截图

关于这个实验返回index的时候,我本来是仿照前面例子的这个部分
写的,但是写完if(it!=contacts_end())的那一句的时候,后面不太知道怎么写,于是就选择了我代码中的另一个普通的方法,而ai给我建议的写法是
return static_cast<int>(std::distance(contacts_.begin(), it));
算出从起点到找到的迭代器的距离
最后的sort函数我也是书写的时候自然而然想到用c++里面的sort()函数来实现,实现的时候有困难,通过这一段代码又学到了新的sort用法,让sort自己挑出a和b,然后比较这两个字典序,return语句执行之后如果返回true,就是告诉算法a比b小,a应该排前面。
浙公网安备 33010602011771号