实验三
任务一
botton.hpp
#pragma once
#include <iostream>
#include <string>
//定义Button类
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>
// 窗口类,定义Window类
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"));//追加元素close,一旦构造函数,就会追加一个元素close
}
inline void Window::display() const {
std::string s(40, '*');//生成一个字符串里面有40个*;
std::cout << s << std::endl;
std::cout << "window : " << title_ << std::endl;//先输出Demo
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";//输出button add alreadt extists
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");//创建一个Window对象v,title是Demo
w.add_button("add");//追加add
w.add_button("remove");//追加remove
w.add_button("modify");//追加modify
w.add_button("add");//已经存在输出add
w.display();//输出
w.close();//输出close
}
int main() {
std::cout << "用组合类模拟简单GUI:\n";
test();
return 0;
}
运行结果:

问题回答:
1.两者是组合关系。std::vector<Button> buttons_ 是值成员,在 Window 对象创建时这个 vector 一起被构造,Window 析构时 vector 也跟着销毁,它的生命周期完全由 Window 管理。
2.1has_button 现在只有 add_button 会调用,作用是添加前先判断这个按钮是否已经存在,用来去重。如果改成公有接口,好处是外部也能直接判断某个按钮在不在;坏处是把内部判断的细节暴露了出去,破坏了封装。对外的接口一般只负责展示、添加这类功能,而去重只是添加操作内部的判断,没必要放到 public 里。
2.2.按照封装的原则,对外只暴露必须的、稳定的、不会轻易破坏对象状态的接口;内部实现细节和会改动状态的辅助函数都放在 private。has_button 只是内部用来判断的工具函数,所以设为 private。
3.第一个接口返回 const std::string&:const 保证返回的字符串不会被修改,而且返回的是引用,不需要拷贝,性能更好。第二个接口返回 std::string,是按值返回,会把字符串拷贝一份出来,有额外的拷贝开销。
4.程序可以正常运行

4.1push_back (Button (xxx)) 的过程是先在外面构造一个临时的 Button 对象,再把这个临时对象拷贝或者移动进 vector 的存储空间,相当于先造好对象再搬进容器。emplace_back (xxx) 是把参数 xxx 传给 vector,由 vector 在内部位置直接原地构造 Button 对象,省去了临时对象的构造和一次拷贝或移动。两者区别在于 push_back 接收的是已经构造好的对象,emplace_back 接收的是构造函数的参数;emplace_back 一般更高效,是 C++11 之后推荐的写法,但最终容器里的内容和程序结果两者是一致的。
4.2any_of 用来判断一段区间里有没有满足条件的元素。first、last 两个迭代器圈出要检查的范围,这里传的是 buttons_.begin () 和 buttons_.end (),也就是整个按钮集合。遍历过程中只要有任意一个元素让条件成立、返回 true,就立刻返回 true,后面不用再看;如果从头走到尾都没有符合条件的,就返回 false。返回值是 bool 类型。
4.3从 buttons_ 的开头到结尾逐个检查,找到第一个标签等于 label 的按钮,返回指向它的迭代器;如果找不到,就返回 buttons_.end ()。
5.
vector 挨个找,数量不大、查得也不多时无所谓;数量极大又高频查找时才可能变慢。换成 map 做键值对应后查找更快,但 map 按字典序排,display () 输出也会跟着变成字典序。
任务二、
源代码
#include <iostream>
#include <vector>
//函数声明
void test1();
void test2();
void output1(const std::vector<int>& v);//函数声明,output1函数,接收一个 const std::vector<int>& 类型的参数,没有返回值。
void output2(const std::vector<int>& v);
void output3(const std::vector<std::vector<int>>& v);//参数是 const std::vector<std::vector<int>>&:一个“元素为 vector<int> 的 vector”的 const 引用,即二维 vector 的只读引用。
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);//创建一个容量大小为5,内容全是42的动态数组
const std::vector<int> v2(v1);//用v2复制拷贝v1
std::cout << "**********拷贝构造后**********\n";
std::cout << "v1: "; output1(v1);
std::cout << "v2: "; output1(v2);
v1[0] = -1;//改v1的第一个元素
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 } };//创建二维vector数组,第0行的元素是1,2,3,第1行的元素是4,5,6,7
const std::vector<std::vector<int>> v2(v1);//复制v1.size()==2,v1[0].size()==3,v1[1].size()==4
std::cout << "**********拷贝构造后**********\n";
std::cout << "v1:\n"; output3(v1);
std::cout << "v2:\n"; output3(v2);
v1[0].push_back(-1);//在第0行后面追加-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();//it 的类型就是 v.begin() 返回的迭代器类型通常是 std::vector<int>::iterator 或 const_iterator)。
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.v1 是用 vector 的填充构造函数造的,里面放了 5 个 42;v2 是用拷贝构造函数从 v1 复制过来的,所以 v2 里也有 5 个 42。
2.v1.size () 是 2,v2.size () 是 2,v1 [0] 这个 vector 的 size 是 3。
3.两者能达到同样的效果,区别是 v1 [0] 用的是 operator [],不做越界检查,速度快;v1.at (0) 会做边界检查,越界就抛异常,更安全。
4.1能。v1 [0].push_back (-1) 在 v1 第 0 行的末尾追加了 -1,这一行变成 {1, 2, 3, -1},大小是 4。然后 const std::vector<int>& r = v1 [0] 让 r 成为 v1 [0] 的引用,r.size ()-1 等于 3,r [3] 取到的就是刚加进去的 -1,所以输出 -1。
4.2好处是 r 是引用,不会再另外拷贝一个 vector,能省内存也省时间。限制是 r 只是 v1 [0] 的别名,一直依赖 v1 活着;v1 要是销毁了,r 就悬空了,所以这种引用适合短期、局部用一下。
5.1是深拷贝。
5.2非 const 版本的返回值是 int&,也就是元素的引用;const 版本返回的是 const int&,只读引用。这个 const 版本必须要有,因为 const 对象只能调用 const 成员函数,如果只写了非 const 的 at (),const 的 vector 就调不了;而 const 版本返回 const int&,也能保证不会通过它去改 const 对象里的数据。
任务三、
源代码
vertorint.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);//返回的是当前对象自身的引用(即 *this)。
int* begin();
int* end();
const int* begin() const;
const int* end() const;
private:
int n_; // 当前数据项个数
int* pdata_; // 数据区
};
inline vectorInt::vectorInt() :n_{ 0 }, pdata_{ nullptr } {//n设置为0,pdata设置成空指针
}
inline vectorInt::vectorInt(int n) : n_{ n }, pdata_{ new int[n] } {//用 new int[n] 动态分配 n 个 int 的内存,把返回的指针作为 pdata_ 的初值
}
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)//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';
}
运行截图

1.1版本 1 比版本 2 多了一句 if (this == &vi) return *this; 的自赋值检查,而且是把新数据复制完之后才 delete [] 旧数据。版本 2 把 delete [] pdata_ 放在最前面,也没有自赋值检查,先把自己的数据释放掉,再去读已经释放的内存,容易出乱码或者直接崩溃,pdata_ 也被破坏了,属于异常不安全。
2.1把 this 从 vectorInt* 转成 const vectorInt*,从而调用 const 版本 at ();否则非 const 函数里直接 this->at (index) 会递归调自己,无限递归。
2.2去掉返回值的 const,把 const int& 转成 int&;对象本身非 const,元素本来可改。
3.1v1.begin() 调用非 const 版本(返回 int*),v2.begin() 调用 const 版本(返回 const int*),编译器根据对象是否 const 选择重载。
3.2迭代器是指针的封装,支持 *、++、!= 等操作,用来遍历容器。
4能正常运行。fill_n 把 pdata_ 起 n_ 个元素填成 value;copy_n 把 vi 的 n_ 个元素复制到目标位置,分别对应构造、拷贝构造和 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) {
n_rows_ = x.n_rows_;
n_cols_ = x.n_cols_;
pdata_ = new double[n_rows_ * 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) {
std::cout << pdata_[i * n_cols_];
for(int j = 1; 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.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';
}
运行截图

问题回答:是。空位被 0 填满后,copy_n 仍会越界读到第 6 个地址,拿到垃圾值;把参数改成 const vector<double>&,靠它自带的 size () 就能避免这种非法访问。
任务五、
源代码
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 = std::find_if(contacts_.begin(), contacts_.end(),
[&](const Contact &c) { return c.get_name() == name; });
if(it == contacts_.end())
return -1;
return static_cast<int>(it - contacts_.begin());
}
// 待补足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();
}
运行截图

问题回答:
1.index () 是拿姓名一个个线性比较找的,用的 ==,所以区分大小写;排序用 std::sort,再配一个按姓名比较的谓词,按字典序从小到大排。新增之后会自动重新排序;重复添加、查找不存在的人、删除不存在的人,都会按要求给出提示。

浙公网安备 33010602011771号