C++和标准库速成(十二)——练习
目录
- 练习1.1
- 题目
- 答案
- 练习1.2
- 题目
- 答案
- 练习1.3
- 题目
- 答案
- 练习1.4
- 题目
- 答案
- 练习1.5
- 题目
- 答案
- 练习1.6
- 题目
- 答案
- 参考
练习1.1
题目
修改下面的Employee结构体,将其放在一个名为HR的名称空间中。你必须对main()中的代码进行那些修改才能使用此新实现?此外,修改代码使用C++20的指派初始化器。
// employee模块接口文件
export module employee;export struct Employee {char firstInitial;char lastInitial;int employeeNumber;int salary;
};
// main
// import <iostream>;
// import <format>;
import std.core;
import employee;int main() {Employee anEmployee;anEmployee.firstInitial = 'J';anEmployee.lastInitial = 'D';anEmployee.employeeNumber = 42;anEmployee.salary = 80'000;std::cout << std::format("Employee: {}{}\n", anEmployee.firstInitial, anEmployee.lastinitial);std::cout << std::format("Number: {}\n", anEmployee.employeeNumber);std::cout << std::format("Salary: ${}\n", anEmployee.salary);
}
答案
// employee模块接口文件
export module employee;namespace HR {export struct Employee {char firstInitial;char lastInitial;int employeeNumber;int salary;};
}
// main()
import std.core;
import employee;int main() {HR::Employee anEmployee{.firstInitial = 'J',.lastInitial = 'D',.employeeNumber = 42,.salary = 80'000};std::cout << std::format("Employee: {}{}\n", anEmployee.firstInitial, anEmployee.lastInitial);std::cout << std::format("Number: {}\n", anEmployee.employeeNumber);std::cout << std::format("Salary: {}\n", anEmployee.salary);
}
练习1.2
题目
以练习1.1的结果为基础,并向Employee添加一个枚举数据成员title,以指定某个雇员是经理,高级工程师还是工程师。你将选用哪种枚举类型?无论需要添加什么,都将其添加到HR名称空间中。在main()函数中测试新的Employee数据成员。使用switch语句为title打印出易于理解的字符串。
答案
// employee模块接口文件
export module employee;namespace HR {export enum class position {MANAGER,ENGINEER,SENIOR_ENGINEER};export struct Employee {char firstInitial;char lastInitial;int employeeNumber;int salary;position title;};
}
// main()
import std.core;
import employee;int main() {std::string title;HR::Employee anEmployee{.firstInitial = 'J',.lastInitial = 'D',.employeeNumber = 42,.salary = 80'000,.title = HR::position::ENGINEER};std::cout << std::format("Employee: {}{}\n", anEmployee.firstInitial, anEmployee.lastInitial);std::cout << std::format("Number: {}\n", anEmployee.employeeNumber);std::cout << std::format("Salary: {}\n", anEmployee.salary);switch (anEmployee.title) {case HR::position::ENGINEER:title = "Engineer";break;case HR::position::MANAGER:title = "Manager";break;case HR::position::SENIOR_ENGINEER:title = "Senior Engineer";break;}if (!title.empty()) {std::cout << std::format("Title: {}\n", title);}
}
练习1.3
题目
使用std::array存储练习1.2中具有不同数据的3个Employee实例,然后使用基于范围的for循环打印出array中的雇员。
答案
// main()
import std.core;
import employee;static const std::string title(HR::position pos) {std::string title;switch (pos) {case HR::position::ENGINEER:title = "Engineer";break;case HR::position::MANAGER:title = "Manager";break;case HR::position::SENIOR_ENGINEER:title = "Senior Engineer";break;}return title;
}static void display(HR::Employee employee) {std::cout << std::format("Employee: {} {}\n", employee.firstInitial, employee.lastInitial);std::cout << std::format("Number: {}\n", employee.employeeNumber);std::cout << std::format("Salary: {}\n", employee.salary);std::cout << std::format("Title: {}\n\n", title(employee.title));
}int main() {std::array<HR::Employee, 3> employees{ {{'J', 'D', 42, 80'000, HR::position::MANAGER },{'A', 'H', 43, 60'000, HR::position::SENIOR_ENGINEER },{'C', 'B', 44, 40'000, HR::position::ENGINEER }}};for (auto& employee : employees) {display(employee);}
}
练习1.4
题目
进行与练习1.3相同的操作,但使用std::vector而不是array,并使用push_back()将元素插入vector中。
答案
// main()
import std.core;
import employee;static const std::string title(HR::position pos) {std::string title;switch (pos) {case HR::position::ENGINEER:title = "Engineer";break;case HR::position::MANAGER:title = "Manager";break;case HR::position::SENIOR_ENGINEER:title = "Senior Engineer";break;}return title;
}static void display(HR::Employee employee) {std::cout << std::format("Employee: {} {}\n", employee.firstInitial, employee.lastInitial);std::cout << std::format("Number: {}\n", employee.employeeNumber);std::cout << std::format("Salary: {}\n", employee.salary);std::cout << std::format("Title: {}\n\n", title(employee.title));
}int main() {HR::Employee employee1 { 'J', 'D', 42, 80'000, HR::position::MANAGER };HR::Employee employee2 { 'A', 'H', 43, 60'000, HR::position::SENIOR_ENGINEER };HR::Employee employee3 { 'C', 'B', 44, 40'000, HR::position::ENGINEER };std::vector<HR::Employee> employees;employees.push_back(employee1);employees.push_back(employee2);employees.push_back(employee3);for ( auto& employee : employees ) {display(employee);}
}
练习1.5
题目
修改下面的AirlineTicket类,以尽可能地使用引用,并正确使用const。
// airline_ticket模块接口文件
export module airline_ticket;// import <string>;
import std.core; // MSVCexport class AirlineTicket {
public:AirlineTicket(); // constructor~AirlineTicket(); // destructordouble calculatePriceInDollars();std::string getPassengerName();void setPassengerName(std::string name);int getNumberOfMiles();void setNumberOfMiles(int miles);bool hasEliteSuperRewardsStatus();void setHasEliteSuperRewardsStatus(bool status);private:std::string m_passengerName;int m_numberOfMiles;bool m_hasEliteSuperRewardsStatus;
};
// airline_ticket模块实现文件
module airline_ticket;AirlineTicket::AirlineTicket() :m_passengerName{ "Unknown Passenger" },m_numberOfMiles{ 0 },m_hasEliteSuperRewardsStatus{ false } {
}AirlineTicket::~AirlineTicket() {// nothong to do in terms of cleanup.
}double AirlineTicket::calculatePriceInDollars() {if (hasEliteSuperRewardsStatus()) {// elite super rewards customers fly for free!return 0;}// the cost of the ticket is the number of milies times 0.1.// real airlines probably have a more complicated formula!return getNumberOfMiles() * 0.1;
}std::string AirlineTicket::getPassengerName() {return m_passengerName;
}void AirlineTicket::setPassengerName(std::string name) {m_passengerName = name;
}int AirlineTicket::getNumberOfMiles() {return m_numberOfMiles;
}void AirlineTicket::setNumberOfMiles(int miles) {m_numberOfMiles = miles;
}bool AirlineTicket::hasEliteSuperRewardsStatus() {return m_hasEliteSuperRewardsStatus;
}void AirlineTicket::setHasEliteSuperRewardsStatus(bool status) {m_hasEliteSuperRewardsStatus = status;
}
答案
// airline_ticket模块接口文件
export module airline_ticket;// import <string>;
import std.core; // MSVCexport class AirlineTicket {
public:AirlineTicket(); // constructor~AirlineTicket(); // destructordouble calculatePriceInDollars() const;const std::string& getPassengerName() const;void setPassengerName(const std::string& name);int getNumberOfMiles() const;void setNumberOfMiles(int miles);bool hasEliteSuperRewardsStatus() const;void setHasEliteSuperRewardsStatus(bool status);private:std::string m_passengerName;int m_numberOfMiles;bool m_hasEliteSuperRewardsStatus;
};
// airline_ticket模块实现文件
module airline_ticket;AirlineTicket::AirlineTicket() :m_passengerName{ "Unknown Passenger" },m_numberOfMiles{ 0 },m_hasEliteSuperRewardsStatus{ false } {
}AirlineTicket::~AirlineTicket() {// nothong to do in terms of cleanup.
}double AirlineTicket::calculatePriceInDollars() const {if (hasEliteSuperRewardsStatus()) {// elite super rewards customers fly for free!return 0;}// the cost of the ticket is the number of milies times 0.1.// real airlines probably have a more complicated formula!return getNumberOfMiles() * 0.1;
}const std::string& AirlineTicket::getPassengerName() const {return m_passengerName;
}void AirlineTicket::setPassengerName(const std::string& name) {m_passengerName = name;
}int AirlineTicket::getNumberOfMiles() const {return m_numberOfMiles;
}void AirlineTicket::setNumberOfMiles(int miles) {m_numberOfMiles = miles;
}bool AirlineTicket::hasEliteSuperRewardsStatus() const {return m_hasEliteSuperRewardsStatus;
}void AirlineTicket::setHasEliteSuperRewardsStatus(bool status) {m_hasEliteSuperRewardsStatus = status;
}
练习1.6
题目
修改练习1.5中的AirlineTicket类,使其包含一个可选的常旅客号码。表示此可选数据成员的最佳方法是什么?添加一个设置器和获取器来设置和获取常旅客号码。修改main()函数以测试你的实现。
答案
// airline_ticket模块接口文件
export module airline_ticket;// import <string>;
import std.core; // MSVCexport class AirlineTicket {
public:AirlineTicket(); // constructor~AirlineTicket(); // destructordouble calculatePriceInDollars();std::string getPassengerName();void setPassengerName(std::string name);int getNumberOfMiles();void setNumberOfMiles(int miles);void setFrequentFlyerNumber(int frequentFlyerNumber);std::optional<int> getFrequentFlyerNumber() const;bool hasEliteSuperRewardsStatus();void setHasEliteSuperRewardsStatus(bool status);private:std::string m_passengerName;int m_numberOfMiles;std::optional<int> m_frequentFlyerNumber;bool m_hasEliteSuperRewardsStatus;
};
// airline_ticket模块实现文件
module airline_ticket;AirlineTicket::AirlineTicket() :m_passengerName{ "Unknown Passenger" },m_numberOfMiles{ 0 },m_hasEliteSuperRewardsStatus{ false } {
}AirlineTicket::~AirlineTicket() {// nothong to do in terms of cleanup.
}double AirlineTicket::calculatePriceInDollars() {if (hasEliteSuperRewardsStatus()) {// elite super rewards customers fly for free!return 0;}// the cost of the ticket is the number of milies times 0.1.// real airlines probably have a more complicated formula!return getNumberOfMiles() * 0.1;
}std::string AirlineTicket::getPassengerName() {return m_passengerName;
}void AirlineTicket::setPassengerName(std::string name) {m_passengerName = name;
}int AirlineTicket::getNumberOfMiles() {return m_numberOfMiles;
}void AirlineTicket::setNumberOfMiles(int miles) {m_numberOfMiles = miles;
}void AirlineTicket::setFrequentFlyerNumber(int frequentFlyerNumber) {m_frequentFlyerNumber = frequentFlyerNumber;
}
std::optional<int> AirlineTicket::getFrequentFlyerNumber() const {return m_frequentFlyerNumber;
}bool AirlineTicket::hasEliteSuperRewardsStatus() {return m_hasEliteSuperRewardsStatus;
}void AirlineTicket::setHasEliteSuperRewardsStatus(bool status) {m_hasEliteSuperRewardsStatus = status;
}
// main()
import std.core;
import airline_ticket;int main() {AirlineTicket myTicket;myTicket.setPassengerName("Sherman T. Socketwrench");myTicket.setNumberOfMiles(700);myTicket.setFrequentFlyerNumber(123'456);const double cost{ myTicket.calculatePriceInDollars() };std::cout << std::format("This ticket will cost ${}\n", cost);const auto frequentFlyerNumber{ myTicket.getFrequentFlyerNumber() };if (frequentFlyerNumber) {std::cout << std::format("Frequent flyer number: {}\n", frequentFlyerNumber.value());}else {std::cout << "No frequent flyer number.\n";}
}
参考
[比] 马克·格雷戈勒著 程序喵大人 惠惠 墨梵 译 C++20高级编程(第五版)
相关文章:
C++和标准库速成(十二)——练习
目录 练习1.1题目答案 练习1.2题目答案 练习1.3题目答案 练习1.4题目答案 练习1.5题目答案 练习1.6题目答案 参考 练习1.1 题目 修改下面的Employee结构体,将其放在一个名为HR的名称空间中。你必须对main()中的代码进行那些修改才能使用此新实现?此外&a…...
DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加导出数据功能
前言:哈喽,大家好,今天给大家分享一篇文章!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加导出数据功能📚页面效果📚指令输入�…...
5、linux c 线程 - 上
【四】线程 1. 线程的创建 #include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*routine)(void *), void *arg); pthread_t *thread:指向线程标识符的指针,用于存储新创建线程的 ID。 const p…...
2024年河南省职业院校 技能大赛高职组 “大数据分析与应用” 赛项任务书(四)
2024 年河南省职业院校 技能大赛高职组 “大数据分析与应用” 赛项任务书(四)) 背景描述:任务一:Hadoop 完全分布式安装配置(25 分)任务二:离线数据处理(25 分࿰…...
Model Context Protocol - Prompts
1. 概述 Model Context Protocol (MCP) 提供了一种标准化的方式,使服务器能够向客户端暴露提示模板(prompts)。Prompts 是服务器提供的结构化消息和指令,用于与语言模型进行交互。客户端可以发现可用的提示、获取其内容ÿ…...
dify创建第一个Agent
1、首先LLM模型必须支持 Function Calling 由于deepseek-R1本地化部署时还不支持,所以使用 qwq模型。 2、创建空白 Agent 3、为Agent添加工具 4、测试 当未添加时间工具时 询问 时间 如下 5、开启时间工具 询问如下...
⭐算法OJ⭐判断二叉搜索树【树的遍历】(C++实现)Validate Binary Search Tree
图论入门【数据结构基础】:什么是树?如何表示树? 之前我们有分别讲解二叉树的三种遍历的相关代码实现: ⭐算法OJ⭐二叉树的前序遍历【树的遍历】(C实现)Binary Tree Preorder Traversal ⭐算法OJ⭐二叉树的…...
深度解析 | Android 13 Launcher3分页指示器改造:横线变圆点实战指南
一、需求背景与技术挑战 在Android 13系统定制开发中,我们面临将Launcher3桌面从传统双层架构优化为现代单层布局的挑战。原生系统采用的分页横线指示器在视觉呈现上存在两点不足: 风格陈旧不符合Material You设计规范 空间占用较大影响屏幕利用率 通…...
2. 商城前端部署
商城客户端前端部署 https://gitee.com/newbee-ltd/newbee-mall-api-go 使用开源新蜂商城的前端,git clone到本地 然后在vscode终端依次输入下列指令(配置好vue3相关环境的前提下): npm install npm i --legacy-peer-deps npm …...
鸿蒙生态开发
鸿蒙生态开发概述 鸿蒙生态是华为基于开源鸿蒙(OpenHarmony)构建的分布式操作系统生态,旨在通过开放共享的模式连接智能终端设备、操作系统和应用服务,覆盖消费电子、工业物联网、智能家居等多个领域。以下从定义与架构、核心技术…...
基于STM32进行FFT滤波并计算插值DA输出
文章目录 一、前言背景二、项目构思1. 确定FFT点数、采样率、采样点数2. 双缓存设计 三、代码实现1. STM32CubeMX配置和HAL库初始化2. 核心代码 四、效果展示和后话五、项目联想与扩展1. 倍频2. 降频3. 插值3.1 线性插值3.2 样条插值 一、前言背景 STM32 对 AD 采样信号进行快…...
【Oracle资源损坏类故障】:详细了解坏块
目录 1、物理坏块与逻辑坏块 1.1、物理坏块 1.2、逻辑坏块 2、两个坏块相关的参数 2.1、db_block_checksum 2.2、db_block_checking 3、检测坏块 3.1、告警日志 3.2、RMAN 3.3、ANALYZE 3.4、数据字典 3.5、DBVERIFY 4、修复坏块 4.1、RMAN修复 4.2、DBMS_REPA…...
996引擎-接口测试:背包
996引擎-接口测试:背包 背包测试NPC参考资料背包测试NPC CONSTANT = require("Envir/QuestDiary/constant/CONSTANT.lua"); MsgUtil = require("Envir/QuestDiary/utils/996/MsgUtil.lua");...
第三十一篇 数据仓库(DW)与商业智能(BI)架构设计与实践指南
目录 一、DW/BI架构核心理论与选型策略1.1 主流架构模式对比(1)Kimball维度建模架构(2)Inmon企业工厂架构(3)混合架构 二、架构设计方法论与实施步骤2.1 维度建模实战指南(1)模型选择…...
智能追踪台灯需求文档
一、项目背景 设计一款具备人体感知与动态追踪能力的智能台灯,实现以下核心目标: 自动开关:检测到人体活动时自动开启光源,无人时关闭以节省能耗。主动追踪:通过机械结构实时调整光照方向,确保用户始终处…...
给语言模型增加知识逻辑校验智能,识别网络信息增量的垃圾模式
给LLM增加逻辑校验模型,赋予其批判性智能。 网络系统上信息不断增长,相当部分是非纯粹的人类生成,而是由各种模型生成输出。模型持续从网络取得信息,生成信息输出到网络,AI生态系统与网络信息池之间陷入信息熵增循环。…...
Electron打包文件生成.exe文件打开即可使用
1 、Electron 打包,包括需要下载的内容和环境配置步骤 注意:Electron 是一个使用 JavaScript、HTML 和 CSS 构建跨平台桌面应用程序的框架 首先需要电脑环境有Node.js 和 npm我之前的文章有关nvm下载node的说明也可以去官网下载 检查是否有node和npm环…...
单播、广播、组播和任播
文章目录 一、单播二、广播三、组播四、任播代码示例: 五、各种播的比较 一、单播 单播(Unicast)是一种网络通信方式,它指的是在网络中从一个源节点到一个单一目标节点对的传输模式。单播传输时,数据包从发送端直接发…...
AI生成移动端贪吃蛇游戏页面,手机浏览器打开即可玩
贪吃蛇游戏可计分,可穿墙,AI生成适配手机浏览器的游戏,代码如下: <!DOCTYPE html> <html lang"zh-CN"> <head> <meta charset"UTF-8"> <meta name"viewport" …...
Cursor+Claude-3.5生成Android app
一、Android Studio下载 https://developer.android.com/studio?hlzh-tw#get-android-studio 等待安装完成 二、新建工程 点击new project 选择Empty Activity 起一个工程名 当弹出这个框时 可以在settings里面选择No proxy 新建好后如下 点击右边模拟器,…...
NLP高频面试题(九)——大模型常见的几种解码方案
大模型常见的几种解码方案 在自然语言生成任务中,如何从模型生成的概率分布中选择合适的词汇,是影响文本质量的关键问题。常见的解码方法包括贪心搜索(Greedy Search)、束搜索(Beam Search)、随机采样&…...
QT Quick(C++)跨平台应用程序项目实战教程 3 — 项目基本设置(窗体尺寸、中文标题、窗体图标、可执行程序图标)
目录 1. 修改程序界面尺寸和标题 2. 窗体图标 3. 修改可执行程序图标 上一章创建好了一个初始Qt Quick项目。本章介绍基本的项目修改方法。 1. 修改程序界面尺寸和标题 修改Main.qml文件,将程序宽度设置为1200,程序高度设置为800。同时修改程序标题…...
Transformers x SwanLab:可视化NLP模型训练(2025最新版)
HuggingFace 的 Transformers 是目前最流行的深度学习训框架之一(100k Star),现在主流的大语言模型(LLaMa系列、Qwen系列、ChatGLM系列等)、自然语言处理模型(Bert系列)等,都在使用T…...
VSCode 抽风之 两个conda环境同时在被激活
出现了神奇的(toolsZCH)(base) 提示符,如下图所示: 原因大概是:conda 环境的双重激活:可能是 conda 环境没有被正确清理或初始化,导致 base 和 toolsZCH 同时被激活。 解决办法就是 :conda deactivate 两次…...
Android项目实战搭建 MVVM架构
View层 具体代码: activity: /*** description:* 普通Activity基类,不带ViewModel,显示基本加载状态* 需要获取到子类的布局id用于databinding的绑定* author YL Chen* date 2024/9/4 21:34* version 1.0*/ abstract class BaseActivity<VB : ViewD…...
Mybatis的基础操作——03
写mybatis代码的方法有两种: 注解xml方式 本篇就介绍XML的方式 使用XML来配置映射语句能够实现复杂的SQL功能,也就是将sql语句写到XML配置文件中。 目录 一、配置XML文件的路径,在resources/mapper 的目录下 二、写持久层代码 1.添加mappe…...
React:React主流组件库对比
1、Material-UI | 官网 | GitHub | GitHub Star: 94.8k Material-UI 是一个实现了 Google Material Design 规范的 React 组件库。 Material UI 包含了大量预构建的 Material Design 组件,覆盖导航、滑块、下拉菜单等各种常用组件,并都提供了高度的可定制…...
奇迹科技:蓝牙网关赋能少儿篮球教育的创新融合案例研究
一、引言 本文研究了福建奇迹运动体育科技有限公司(简称‘奇迹科技’)如何利用其创新产品体系和桂花网蓝牙网关M1500,与少儿篮球教育实现深度融合。重点分析其在提升教学效果、保障训练安全、优化个性化教学等方面的实践与成效,为…...
分享最近前端面试遇到的一些问题
前情提要(分享个人情况,可以直接跳过) 先说一下我的个人情况,我是2026届的,目前是在找前端实习。 3月初,从3月3日开始在Boss上投简历。 分享我的个人故事,不想看可以直接滑到下面,…...
嵌入式基础知识学习:SPI通信协议是什么?
SPI(Serial Peripheral Interface)是串行外设接口的缩写,是一种广泛应用于嵌入式系统的高速同步串行通信协议,由摩托罗拉公司于20世纪80年代提出。以下是其核心要点: 一、SPI的核心定义与特点 基本特性 全双工同步通信…...
