C++和标准库速成(十二)——练习

news2025/3/24 23:16:32

目录

  • 练习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; // MSVC

export class AirlineTicket {
public:
	AirlineTicket(); // constructor
	~AirlineTicket(); // destructor

	double 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; // MSVC

export class AirlineTicket {
public:
	AirlineTicket(); // constructor
	~AirlineTicket(); // destructor

	double 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; // MSVC

export class AirlineTicket {
public:
	AirlineTicket(); // constructor
	~AirlineTicket(); // destructor

	double 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高级编程(第五版)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2320413.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加导出数据功能

前言:哈喽,大家好,今天给大家分享一篇文章!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加导出数据功能📚页面效果📚指令输入�…

2024年河南省职业院校 技能大赛高职组 “大数据分析与应用” 赛项任务书(四)

2024 年河南省职业院校 技能大赛高职组 “大数据分析与应用” 赛项任务书&#xff08;四&#xff09;&#xff09; 背景描述&#xff1a;任务一&#xff1a;Hadoop 完全分布式安装配置&#xff08;25 分&#xff09;任务二&#xff1a;离线数据处理&#xff08;25 分&#xff0…

dify创建第一个Agent

1、首先LLM模型必须支持 Function Calling 由于deepseek-R1本地化部署时还不支持&#xff0c;所以使用 qwq模型。 2、创建空白 Agent 3、为Agent添加工具 4、测试 当未添加时间工具时 询问 时间 如下 5、开启时间工具 询问如下

⭐算法OJ⭐判断二叉搜索树【树的遍历】(C++实现)Validate Binary Search Tree

图论入门【数据结构基础】&#xff1a;什么是树&#xff1f;如何表示树&#xff1f; 之前我们有分别讲解二叉树的三种遍历的相关代码实现&#xff1a; ⭐算法OJ⭐二叉树的前序遍历【树的遍历】&#xff08;C实现&#xff09;Binary Tree Preorder Traversal ⭐算法OJ⭐二叉树的…

2. 商城前端部署

商城客户端前端部署 https://gitee.com/newbee-ltd/newbee-mall-api-go 使用开源新蜂商城的前端&#xff0c;git clone到本地 然后在vscode终端依次输入下列指令&#xff08;配置好vue3相关环境的前提下&#xff09;&#xff1a; npm install npm i --legacy-peer-deps npm …

鸿蒙生态开发

鸿蒙生态开发概述 鸿蒙生态是华为基于开源鸿蒙&#xff08;OpenHarmony&#xff09;构建的分布式操作系统生态&#xff0c;旨在通过开放共享的模式连接智能终端设备、操作系统和应用服务&#xff0c;覆盖消费电子、工业物联网、智能家居等多个领域。以下从定义与架构、核心技术…

基于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");

Electron打包文件生成.exe文件打开即可使用

1 、Electron 打包&#xff0c;包括需要下载的内容和环境配置步骤 注意&#xff1a;Electron 是一个使用 JavaScript、HTML 和 CSS 构建跨平台桌面应用程序的框架 首先需要电脑环境有Node.js 和 npm我之前的文章有关nvm下载node的说明也可以去官网下载 检查是否有node和npm环…

单播、广播、组播和任播

文章目录 一、单播二、广播三、组播四、任播代码示例&#xff1a; 五、各种播的比较 一、单播 单播&#xff08;Unicast&#xff09;是一种网络通信方式&#xff0c;它指的是在网络中从一个源节点到一个单一目标节点对的传输模式。单播传输时&#xff0c;数据包从发送端直接发…

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 新建好后如下 点击右边模拟器&#xff0c…

QT Quick(C++)跨平台应用程序项目实战教程 3 — 项目基本设置(窗体尺寸、中文标题、窗体图标、可执行程序图标)

目录 1. 修改程序界面尺寸和标题 2. 窗体图标 3. 修改可执行程序图标 上一章创建好了一个初始Qt Quick项目。本章介绍基本的项目修改方法。 1. 修改程序界面尺寸和标题 修改Main.qml文件&#xff0c;将程序宽度设置为1200&#xff0c;程序高度设置为800。同时修改程序标题…

Transformers x SwanLab:可视化NLP模型训练(2025最新版)

HuggingFace 的 Transformers 是目前最流行的深度学习训框架之一&#xff08;100k Star&#xff09;&#xff0c;现在主流的大语言模型&#xff08;LLaMa系列、Qwen系列、ChatGLM系列等&#xff09;、自然语言处理模型&#xff08;Bert系列&#xff09;等&#xff0c;都在使用T…

VSCode 抽风之 两个conda环境同时在被激活

出现了神奇的(toolsZCH)(base) 提示符&#xff0c;如下图所示&#xff1a; 原因大概是&#xff1a;conda 环境的双重激活&#xff1a;可能是 conda 环境没有被正确清理或初始化&#xff0c;导致 base 和 toolsZCH 同时被激活。 解决办法就是 &#xff1a;conda deactivate 两次…

Mybatis的基础操作——03

写mybatis代码的方法有两种&#xff1a; 注解xml方式 本篇就介绍XML的方式 使用XML来配置映射语句能够实现复杂的SQL功能&#xff0c;也就是将sql语句写到XML配置文件中。 目录 一、配置XML文件的路径&#xff0c;在resources/mapper 的目录下 二、写持久层代码 1.添加mappe…

React:React主流组件库对比

1、Material-UI | 官网 | GitHub | GitHub Star: 94.8k Material-UI 是一个实现了 Google Material Design 规范的 React 组件库。 Material UI 包含了大量预构建的 Material Design 组件&#xff0c;覆盖导航、滑块、下拉菜单等各种常用组件&#xff0c;并都提供了高度的可定制…

python每日十题(6)

】函数定义&#xff1a;函数是指一组语句的集合通过一个名字&#xff08;函数名&#xff09;封装起来&#xff0c;要想执行这个函数&#xff0c;只需要调用其函数名即可。函数能提高应用的模块性和代码的重复利用率 在Python语言中&#xff0c;用关键字class来定义类 在Python语…

1.Go - Hello World

1.安装Go依赖 https://go.dev/dl/ 根据操作系统选择适合的依赖&#xff0c;比如windows&#xff1a; 2.配置环境变量 右键此电脑 - 属性 - 环境变量 PS&#xff1a; GOROOT&#xff1a;Go依赖路径&#xff1b; GOPATH&#xff1a;Go项目路径&#xff1b; …

优先队列 priority_queue详解

说到&#xff0c;priority_queue优先队列。必须先要了解啥是堆与运算符重载(我在下方有解释)。 否则只知皮毛&#xff0c;极易忘记寸步难行。 但在开头&#xff0c;还是简单的说下怎么用 首先&#xff0c;你需要调用 #include <queue> 在main函数中&#xff0c;声明…