一、实验结论
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; }; Button::Button(const std::string &label_): label{label_} {}
window.hpp
#pragma once #include <iostream> #include <vector> #include <algorithm> #include "button.hpp" 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; private: std::string title; std::vector<Button> buttons; }; inline const std::string& Button::get_label() const { return label; } inline void Button::click() { std::cout << "Button '" << label << "' clicked\n"; } 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(); }
是。Window类包含vector成员,体现“has-a”关系,Button对象生命周期由Window管理。 问题2: bool has_button(...) 被设计为私有。思考并回答: (1)改为公有的优点/风险: 优点:用户可直接查询按钮是否存在,灵活性高。 风险:暴露内部实现细节,可能被误用(如外部直接依赖按钮标签唯一性),破坏封装性。 (2)判断public/private的原则: public:用户需直接调用的接口(如add_button、display),或类对外提供的核心服务。 private:仅为内部实现细节(如has_button用于辅助add_button)、可能破坏对象状态(如直接修改内部容器)、或用户无需知晓的逻辑。 问题4:push_back(Button(xxx)) 与 emplace_back(xxx) 的差别 push_back:先构造临时Button对象,再拷贝/移动到容器,多一次拷贝/移动开销。 emplace_back:直接在容器内存中构造对象,省去临时对象拷贝/移动,效率更高。 程序中两者均可正常运行,因Button构造简单,差异不明显。 2.实验任务2 程序源代码 task2.cpp #include <iostream> #include <vector> #include <stdexcept> 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(); } 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.at(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: "; output3(v1); std::cout << "v2: "; output3(v2); v1.at(0).push_back(-1); std::cout << "**********修改v1[0]后**********\n"; std::cout << "v1: \n"; output3(v1); std::cout << "v2: \n"; output3(v2); } void output1(const std::vector<int> &v) { if(v.size() == 0) { std::cout << '\n'; return; } std::cout << v.at(0); for(auto i = 1; i < v.size(); ++i) std::cout << ", " << v.at(i); std::cout << '\n'; } 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'; } void output3(const std::vector<std::vector<int>>& v) { if(v.size() == 0) { std::cout << '\n'; return; } for(auto &i: v) output2(i); } 运行测试截图 问题1:测试模块1中两行代码的构造及v1、v2数据项 v1(5, 42):构造含5个值为42的元素的vector;v2(v1):拷贝构造v2。 v1、v2均含5个值为42的数据项。 问题2:测试模块2中执行后v1.size()、v2.size()、v1[0].size() v1.size()=2(外层vector含2个元素),v2.size()=2,v1[0].size()=3(内层第一个vector含3个元素)。 问题3:v1.at(0)=-1与v1[0]=-1的区别 能实现同等效果。at()会边界检查(越界抛out_of_range),[]不检查(越界行为未定义)。 问题4:v1.at(0).push_back(-1)后 (1)不能输出-1。因v2是v1的拷贝,修改v1[0]不影响v2,v2[0]仍为{1,2,3}。 (2)const &接收返回值可避免拷贝大对象,节省内存;限制是不能修改引用对象。 问题5:反向推断 (1)vector复制构造实现深复制(修改原对象副本不变)。 (2)v为vector时,v.at(0)返回int&;v为const vector时,返回const int&。因此at()必须提供const重载以支持const对象访问。 3.实验任务3 程序源代码 vectorInt.hpp #pragma once #include <iostream> 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 *ptr; }; vectorInt::vectorInt():n{0}, ptr{nullptr} {} vectorInt::vectorInt(int n_): n{n_}, ptr{new int[n]} {} vectorInt::vectorInt(int n_, int value): n{n_}, ptr{new int[n_]} { for(auto i = 0; i < n; ++i) ptr[i] = value; } vectorInt::vectorInt(const vectorInt &vi): n{vi.n}, ptr{new int[n]} { for(auto i = 0; i < n; ++i) ptr[i] = vi.ptr[i]; } vectorInt::~vectorInt() { delete [] ptr; } int vectorInt::size() const { return n; } const int& vectorInt::at(int index) const { if(index < 0 || index >= n) { std::cerr << "IndexError: index out of range\n"; std::exit(1); } return ptr[index]; } int& vectorInt::at(int index) { if(index < 0 || index >= n) { std::cerr << "IndexError: index out of range\n"; std::exit(1); } return ptr[index]; } vectorInt& vectorInt::assign(const vectorInt &vi) { if(this == &vi) return *this; int *ptr_tmp = new int[vi.n]; for(int i = 0; i < vi.n; ++i) ptr_tmp[i] = vi.ptr[i]; delete[] ptr; n = vi.n; ptr = ptr_tmp; return *this; } int* vectorInt::begin() { return ptr; } int* vectorInt::end() { return ptr+n; } const int* vectorInt::begin() const { return ptr; } const int* vectorInt::end() const { return ptr+n; } task3.cpp #include "vectorInt.hpp" #include <iostream> void test1(); void test2(); void output1(const vectorInt &vi); void output2(const vectorInt &vi); int main() { std::cout << "测试1: \n"; test1(); std::cout << "\n测试2: \n"; test2(); } 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); } 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'; } 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:当前验证性代码中, vectorInt 接口 assign 实现是安全版本。如果把 assign 实现改成版本2,逐条指出版本 2存在的安全隐患和缺陷 版本2直接delete[] ptr后分配新内存,若new抛出异常(如内存不足),原ptr已被释放,对象处于无效状态(资源泄漏+野指针)。安全版本先分配tmp内存,成功后再释放原ptr,保证异常安全。 问题2:当前验证性代码中,重载接口 at 内部代码完全相同。若把非 const 版本改成如下实现,可消除重复并遵循“最小化接口”原则(未来如需更新接口,只更新const接口,另一个会同步)。 (1)static_cast<const vectorInt*>(this):将当前对象指针转换为const指针。转换前this类型为vectorInt*,转换后为const vectorInt*。目的是复用const版本的at()实现,避免代码重复。 (2)const_cast<int&>:去除const属性。转换前返回类型为const int&,转换后为int&。目的是将const引用的返回值转为非const引用,供非const对象修改。 问题3: (1) v1.begin()(v1为非const):调用非const版本int* begin(),返回可修改指针。 v2.begin()(v2为const):调用const版本const int* begin() const,返回只读指针。 适配场景:非const对象需修改元素用非const迭代器,const对象只读访问用const迭代器。 问题4:以下两个构造函数及 assign 接口实现,都包含内存块的赋值/复制操作。使用算法库 改写是否可以?回答这3行更新代码的功能。 std::fill_n(ptr, n, value):将ptr指向的内存块前n个元素赋值为value。 std::copy_n(vi.ptr, vi.n, ptr):将vi.ptr指向的前vi.n个元素复制到ptr指向的内存。 三行更新代码均通过算法库实现内存块复制/填充,替代手动循环,更简洁安全。 4.实验任务4 matrix.hpp #pragma once class Matrix { public: Matrix(int rows_, int cols_, double value = 0); Matrix(int rows_, double value = 0); Matrix(const Matrix &x); ~Matrix(); void set(const double *pvalue, int size); void clear(); const double& at(int i, int j) const; double& at(int i, int j); int rows() const; int cols() const; void print() const; private: int n_rows; int n_cols; double *ptr; }; matrix.cpp #include "matrix.hpp" #include <iostream> #include <cstdlib> #include <cstring> Matrix::Matrix(int rows_, int cols_, double value): n_rows(rows_), n_cols(cols_) { ptr = new double[n_rows * n_cols]; for(int i = 0; i < n_rows * n_cols; ++i) ptr[i] = value; } Matrix::Matrix(int rows_, double value): Matrix(rows_, rows_, value) {} Matrix::Matrix(const Matrix &x): n_rows(x.n_rows), n_cols(x.n_cols) { ptr = new double[n_rows * n_cols]; memcpy(ptr, x.ptr, n_rows * n_cols * sizeof(double)); } Matrix::~Matrix() { delete[] ptr; } void Matrix::set(const double *pvalue, int size) { if(size != n_rows * n_cols) { std::cerr << "Error: size mismatch\n"; std::exit(1); } memcpy(ptr, pvalue, size * sizeof(double)); } void Matrix::clear() { memset(ptr, 0, n_rows * n_cols * sizeof(double)); } const double& Matrix::at(int i, int j) const { if(i < 0 || i >= n_rows || j < 0 || j >= n_cols) { std::cerr << "IndexError: out of range\n"; std::exit(1); } return ptr[i * n_cols + j]; } double& Matrix::at(int i, int j) { if(i < 0 || i >= n_rows || j < 0 || j >= n_cols) { std::cerr << "IndexError: out of range\n"; std::exit(1); } return ptr[i * n_cols + 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 << at(i, j); if(j < n_cols - 1) std::cout << " "; } std::cout << '\n'; } } task4.cpp #include <iostream> #include <cstdlib> #include "matrix.hpp" 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(); } 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.set(x, n*m); Matrix m2(m, n); m2.set(x, m*n); Matrix m3(n); m3.set(x, n*n); std::cout << "矩阵对象m1: \n"; m1.print(); std::cout << "矩阵对象m2: \n"; m2.print(); std::cout << "矩阵对象m3: \n"; m3.print(); } void test2() { Matrix m1(2, 3, -1); const Matrix m2(m1); std::cout << "矩阵对象m1: \n"; m1.print(); std::cout << "矩阵对象m2: \n"; m2.print(); m1.clear(); m1.at(0, 0) = 1; std::cout << "m1更新后: \n矩阵对象m1第0行 "; output(m1, 0); std::cout << "矩阵对象m2第0行: "; output(m2, 0); } void output(const Matrix &m, int row_index) { if(row_index < 0 || row_index >= m.rows()) { std::cerr << "IndexError: row index out of range\n"; std::exit(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'; } 运行测试截图 拓展思考 用std::vector<double>替换double*ptr:无需手动管理内存(RAII自动释放),复制构造/赋值自动深拷贝,异常安全,代码更简洁(省去析构、拷贝构造手动实现),性能无损(连续内存),体现“零成本抽象”。 5.实验任务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; }; Contact::Contact(const std::string &name_, const std::string &phone_):name{name_}, phone{phone_} {} const std::string& Contact::get_name() const { return name; } const std::string& Contact::get_phone() const { return phone; } void Contact::display() const { std::cout << name << ", " << phone; } contactBook.hpp #pragma once #include <iostream> #include <string> #include <vector> #include <algorithm> #include "contact.hpp" 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; void sort(); private: std::vector<Contact> contacts; }; 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"; } 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"; } 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'; } void ContactBook::display() const { for(auto &c: contacts) { c.display(); std::cout << '\n'; } } size_t ContactBook::size() const { return contacts.size(); } int ContactBook::index(const std::string &name) const { for(size_t i = 0; i < contacts.size(); ++i) if(contacts[i].get_name() == name) return i; return -1; } 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"); } int main() { test(); } 运行测试截图 拓展思考 后续迭代方向:增加修改联系人(update)、数据校验(手机号格式)、异常处理(如空姓名)、持久化(文件存储)、分组管理(嵌套vector)、模糊检索(字符串匹配算法)。扩展时需保持接口兼容(如新增update不影响原有add/remove),用继承或多态优化结构。
(1)改为公有的优点/风险:
优点:用户可直接查询按钮是否存在,灵活性高。
风险:暴露内部实现细节,可能被误用(如外部直接依赖按钮标签唯一性),破坏封装性。
(2)判断public/private的原则:
public:用户需直接调用的接口(如add_button、display),或类对外提供的核心服务。
private:仅为内部实现细节(如has_button用于辅助add_button)、可能破坏对象状态(如直接修改内部容器)、或用户无需知晓的逻辑。
push_back:先构造临时Button对象,再拷贝/移动到容器,多一次拷贝/移动开销。
emplace_back:直接在容器内存中构造对象,省去临时对象拷贝/移动,效率更高。
程序中两者均可正常运行,因Button构造简单,差异不明显。
task2.cpp
#include <iostream> #include <vector> #include <stdexcept> 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(); } 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.at(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: "; output3(v1); std::cout << "v2: "; output3(v2); v1.at(0).push_back(-1); std::cout << "**********修改v1[0]后**********\n"; std::cout << "v1: \n"; output3(v1); std::cout << "v2: \n"; output3(v2); } void output1(const std::vector<int> &v) { if(v.size() == 0) { std::cout << '\n'; return; } std::cout << v.at(0); for(auto i = 1; i < v.size(); ++i) std::cout << ", " << v.at(i); std::cout << '\n'; } 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'; } void output3(const std::vector<std::vector<int>>& v) { if(v.size() == 0) { std::cout << '\n'; return; } for(auto &i: v) output2(i); }
v1(5, 42):构造含5个值为42的元素的vector;v2(v1):拷贝构造v2。
v1(5, 42)
v2(v1)
v1、v2均含5个值为42的数据项。
v1.size()=2(外层vector含2个元素),v2.size()=2,v1[0].size()=3(内层第一个vector含3个元素)。
能实现同等效果。at()会边界检查(越界抛out_of_range),[]不检查(越界行为未定义)。
at()
[]
(1)不能输出-1。因v2是v1的拷贝,修改v1[0]不影响v2,v2[0]仍为{1,2,3}。
(2)const &接收返回值可避免拷贝大对象,节省内存;限制是不能修改引用对象。
const &
(1)vector复制构造实现深复制(修改原对象副本不变)。
(2)v为vector时,v.at(0)返回int&;v为const vector时,返回const int&。因此at()必须提供const重载以支持const对象访问。
int&
const int&
vectorInt.hpp
#pragma once #include <iostream> 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 *ptr; }; vectorInt::vectorInt():n{0}, ptr{nullptr} {} vectorInt::vectorInt(int n_): n{n_}, ptr{new int[n]} {} vectorInt::vectorInt(int n_, int value): n{n_}, ptr{new int[n_]} { for(auto i = 0; i < n; ++i) ptr[i] = value; } vectorInt::vectorInt(const vectorInt &vi): n{vi.n}, ptr{new int[n]} { for(auto i = 0; i < n; ++i) ptr[i] = vi.ptr[i]; } vectorInt::~vectorInt() { delete [] ptr; } int vectorInt::size() const { return n; } const int& vectorInt::at(int index) const { if(index < 0 || index >= n) { std::cerr << "IndexError: index out of range\n"; std::exit(1); } return ptr[index]; } int& vectorInt::at(int index) { if(index < 0 || index >= n) { std::cerr << "IndexError: index out of range\n"; std::exit(1); } return ptr[index]; } vectorInt& vectorInt::assign(const vectorInt &vi) { if(this == &vi) return *this; int *ptr_tmp = new int[vi.n]; for(int i = 0; i < vi.n; ++i) ptr_tmp[i] = vi.ptr[i]; delete[] ptr; n = vi.n; ptr = ptr_tmp; return *this; } int* vectorInt::begin() { return ptr; } int* vectorInt::end() { return ptr+n; } const int* vectorInt::begin() const { return ptr; } const int* vectorInt::end() const { return ptr+n; }
task3.cpp
#include "vectorInt.hpp" #include <iostream> void test1(); void test2(); void output1(const vectorInt &vi); void output2(const vectorInt &vi); int main() { std::cout << "测试1: \n"; test1(); std::cout << "\n测试2: \n"; test2(); } 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); } 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'; } 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直接delete[] ptr后分配新内存,若new抛出异常(如内存不足),原ptr已被释放,对象处于无效状态(资源泄漏+野指针)。安全版本先分配tmp内存,成功后再释放原ptr,保证异常安全。
delete[] ptr
new
(1)static_cast<const vectorInt*>(this):将当前对象指针转换为const指针。转换前this类型为vectorInt*,转换后为const vectorInt*。目的是复用const版本的at()实现,避免代码重复。
static_cast<const vectorInt*>(this)
this
vectorInt*
const vectorInt*
(2)const_cast<int&>:去除const属性。转换前返回类型为const int&,转换后为int&。目的是将const引用的返回值转为非const引用,供非const对象修改。
const_cast<int&>
(1)
v1.begin()(v1为非const):调用非const版本int* begin(),返回可修改指针。
v1.begin()
int* begin()
v2.begin()(v2为const):调用const版本const int* begin() const,返回只读指针。
v2.begin()
const int* begin() const
适配场景:非const对象需修改元素用非const迭代器,const对象只读访问用const迭代器。
std::fill_n(ptr, n, value):将ptr指向的内存块前n个元素赋值为value。
std::fill_n(ptr, n, value)
std::copy_n(vi.ptr, vi.n, ptr):将vi.ptr指向的前vi.n个元素复制到ptr指向的内存。
std::copy_n(vi.ptr, vi.n, ptr)
三行更新代码均通过算法库实现内存块复制/填充,替代手动循环,更简洁安全。
matrix.hpp
#pragma once class Matrix { public: Matrix(int rows_, int cols_, double value = 0); Matrix(int rows_, double value = 0); Matrix(const Matrix &x); ~Matrix(); void set(const double *pvalue, int size); void clear(); const double& at(int i, int j) const; double& at(int i, int j); int rows() const; int cols() const; void print() const; private: int n_rows; int n_cols; double *ptr; };
matrix.cpp
#include "matrix.hpp" #include <iostream> #include <cstdlib> #include <cstring> Matrix::Matrix(int rows_, int cols_, double value): n_rows(rows_), n_cols(cols_) { ptr = new double[n_rows * n_cols]; for(int i = 0; i < n_rows * n_cols; ++i) ptr[i] = value; } Matrix::Matrix(int rows_, double value): Matrix(rows_, rows_, value) {} Matrix::Matrix(const Matrix &x): n_rows(x.n_rows), n_cols(x.n_cols) { ptr = new double[n_rows * n_cols]; memcpy(ptr, x.ptr, n_rows * n_cols * sizeof(double)); } Matrix::~Matrix() { delete[] ptr; } void Matrix::set(const double *pvalue, int size) { if(size != n_rows * n_cols) { std::cerr << "Error: size mismatch\n"; std::exit(1); } memcpy(ptr, pvalue, size * sizeof(double)); } void Matrix::clear() { memset(ptr, 0, n_rows * n_cols * sizeof(double)); } const double& Matrix::at(int i, int j) const { if(i < 0 || i >= n_rows || j < 0 || j >= n_cols) { std::cerr << "IndexError: out of range\n"; std::exit(1); } return ptr[i * n_cols + j]; } double& Matrix::at(int i, int j) { if(i < 0 || i >= n_rows || j < 0 || j >= n_cols) { std::cerr << "IndexError: out of range\n"; std::exit(1); } return ptr[i * n_cols + 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 << at(i, j); if(j < n_cols - 1) std::cout << " "; } std::cout << '\n'; } }
task4.cpp
#include <iostream> #include <cstdlib> #include "matrix.hpp" 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(); } 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.set(x, n*m); Matrix m2(m, n); m2.set(x, m*n); Matrix m3(n); m3.set(x, n*n); std::cout << "矩阵对象m1: \n"; m1.print(); std::cout << "矩阵对象m2: \n"; m2.print(); std::cout << "矩阵对象m3: \n"; m3.print(); } void test2() { Matrix m1(2, 3, -1); const Matrix m2(m1); std::cout << "矩阵对象m1: \n"; m1.print(); std::cout << "矩阵对象m2: \n"; m2.print(); m1.clear(); m1.at(0, 0) = 1; std::cout << "m1更新后: \n矩阵对象m1第0行 "; output(m1, 0); std::cout << "矩阵对象m2第0行: "; output(m2, 0); } void output(const Matrix &m, int row_index) { if(row_index < 0 || row_index >= m.rows()) { std::cerr << "IndexError: row index out of range\n"; std::exit(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'; }
用std::vector<double>替换double*ptr:无需手动管理内存(RAII自动释放),复制构造/赋值自动深拷贝,异常安全,代码更简洁(省去析构、拷贝构造手动实现),性能无损(连续内存),体现“零成本抽象”。
std::vector<double>
double*ptr
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; }; Contact::Contact(const std::string &name_, const std::string &phone_):name{name_}, phone{phone_} {} const std::string& Contact::get_name() const { return name; } const std::string& Contact::get_phone() const { return phone; } void Contact::display() const { std::cout << name << ", " << phone; }
contactBook.hpp
#pragma once #include <iostream> #include <string> #include <vector> #include <algorithm> #include "contact.hpp" 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; void sort(); private: std::vector<Contact> contacts; }; 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"; } 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"; } 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'; } void ContactBook::display() const { for(auto &c: contacts) { c.display(); std::cout << '\n'; } } size_t ContactBook::size() const { return contacts.size(); } int ContactBook::index(const std::string &name) const { for(size_t i = 0; i < contacts.size(); ++i) if(contacts[i].get_name() == name) return i; return -1; } 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"); } int main() { test(); }
后续迭代方向:增加修改联系人(update)、数据校验(手机号格式)、异常处理(如空姓名)、持久化(文件存储)、分组管理(嵌套vector)、模糊检索(字符串匹配算法)。扩展时需保持接口兼容(如新增update不影响原有add/remove),用继承或多态优化结构。