《C++游戏编程入门》第4章 标准模板库: Hangman

2024-03-12 09:12

本文主要是介绍《C++游戏编程入门》第4章 标准模板库: Hangman,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《C++游戏编程入门》第4章 标准模板库: Hangman

    • 4.1 标准模板库
    • 4.2 vector
        • 04.heros_inventory2.cpp
    • 4.3 使用迭代器
        • 04.heros_inventory3.cpp
    • 4.4 使用算法
        • 04.high_scores.cpp
    • 4.5 理解向量性能
    • 4.6 其他STL容器
    • 4.7 Hangman简介
        • 04.hangman.cpp

4.1 标准模板库

Standard Template Library,提供算法、容器和迭代器等。

4.2 vector

动态数组。
优势:

  • 根据需要动态增长。
  • 和STL算法使用,获得查找排序等功能。

缺点:

  • 额外内存开销。
  • 增长时可能性能损失。
  • 某些游戏控制台系统无法使用向量。
04.heros_inventory2.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;int main()
{vector<string> inventory; // 声明// 添加元素inventory.push_back("sword");inventory.push_back("armor");inventory.push_back("shield");cout << "You have " << inventory.size() << " items.\n"; // 向量大小cout << "\nYour items:\n";for (unsigned int i = 0; i < inventory.size(); ++i){cout << inventory[i] << endl; // 向量索引}cout << "\nYou trade your sword for a battle axe.";inventory[0] = "battle axe"; // 向量元素赋值cout << "\nYour items:\n";for (unsigned int i = 0; i < inventory.size(); ++i){cout << inventory[i] << endl;}cout << "\nThe item name '" << inventory[0] << "' has ";cout << inventory[0].size() << " letters in it.\n";cout << "\nYour shield is destroyed in a fierce battle.";inventory.pop_back(); // 移除最后一个元素cout << "\nYour items:\n";for (unsigned int i = 0; i < inventory.size(); ++i){cout << inventory[i] << endl;}cout << "\nYou were robbed of all of your possessions by a thief.";inventory.clear();	   // 移除所有元素if (inventory.empty()) // 判断是否为空{cout << "\nYou have nothing.\n";}else{cout << "\nYou have at least one item.\n";}return 0;
}

4.3 使用迭代器

迭代器标识容器中某个特定元素的值,引用元素。

04.heros_inventory3.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;int main()
{vector<string> inventory;inventory.push_back("sword");inventory.push_back("armor");inventory.push_back("shield");vector<string>::iterator myIterator; // 迭代器声明vector<string>::const_iterator iter; // 常量迭代器,不能修改相应元素cout << "Your items:\n";for (iter = inventory.cbegin(); iter != inventory.cend(); ++iter){cout << *iter << endl;}cout << "\nYou trade your sword for a battle axe.";myIterator = inventory.begin();*myIterator = "battle axe";cout << "\nYour items:\n"; // 循环访问向量// 第一个元素,最后一个元素之后,更新for (iter = inventory.begin(); iter != inventory.end(); ++iter){cout << *iter << endl; // 解引用}cout << "\nThe item name '" << *myIterator << "' has ";cout << (*myIterator).size() << " letters in it.\n";cout << "\nThe item name '" << *myIterator << "' has ";cout << myIterator->size() << " letters in it.\n";cout << "\nYou recover a crossbow from a slain enemy.";inventory.insert(inventory.begin(), "crossbow"); // 插入元素cout << "\nYour items:\n";for (iter = inventory.begin(); iter != inventory.end(); ++iter){cout << *iter << endl;}cout << "\nYour armor is destroyed in a fierce battle.";inventory.erase((inventory.begin() + 2)); // 移除元素cout << "\nYour items:\n";for (iter = inventory.begin(); iter != inventory.end(); ++iter){cout << *iter << endl;}return 0;
}

4.4 使用算法

泛型,同样算法用于不同容器类型的元素。

04.high_scores.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>
using namespace std;int main()
{vector<int>::const_iterator iter;cout << "Creating a list of scores.";vector<int> scores;scores.push_back(1500);scores.push_back(3500);scores.push_back(7500);cout << "\nHigh Scores:\n";for (iter = scores.begin(); iter != scores.end(); ++iter){cout << *iter << endl;}cout << "\nFinding a score.";int score;cout << "\nEnter a score to find: ";cin >> score;iter = find(scores.begin(), scores.end(), score); // 查找if (iter != scores.end()){cout << "Score found.\n";}else{cout << "Score not found.\n";}cout << "\nRandomizing scores.";srand(static_cast<unsigned int>(time(0)));random_shuffle(scores.begin(), scores.end()); // 随机重排cout << "\nHigh Scores:\n";for (iter = scores.begin(); iter != scores.end(); ++iter){cout << *iter << endl;}cout << "\nSorting scores.";sort(scores.begin(), scores.end()); // 排序cout << "\nHigh Scores:\n";for (iter = scores.begin(); iter != scores.end(); ++iter){cout << *iter << endl;}string word = "High Scores";random_shuffle(word.begin(), word.end());for (auto it = word.cbegin(); it != word.cend(); ++it)cout << *it << endl;return 0;
}

4.5 理解向量性能

向量添加新元素超过当前大小时,重新分配内存,可能全部元素重新复制,导致性能损失。
capacity()向量容量,预先多分配空间。
reserve()扩充容量。
push_back()或pop_back(),尾部添加或移除元素效率高。
insert()或erase(),中间添加或移除元素效率底。

4.6 其他STL容器

顺序型容器:依次检索元素值。
关联型容器:基于键值检索元素值。

deque、list、map、multimap、multiset、priority_queue、queue、set、stack、vector

4.7 Hangman简介

04.hangman.cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cctype>
using namespace std;int main()
{// 常量、变量初始化const int MAX_WRONG = 8; // maximum number of incorrect guesses allowedvector<string> words; // collection of possible words to guesswords.push_back("GUESS");words.push_back("HANGMAN");words.push_back("DIFFICULT");srand(static_cast<unsigned int>(time(0)));random_shuffle(words.begin(), words.end());const string THE_WORD = words[0];   // word to guessint wrong = 0;                      // number of incorrect guessesstring soFar(THE_WORD.size(), '-'); // word guessed so farstring used = "";                   // letters already guessedcout << "Welcome to Hangman.  Good luck!\n";// main loopwhile ((wrong < MAX_WRONG) && (soFar != THE_WORD)){cout << "\n\nYou have " << (MAX_WRONG - wrong);cout << " incorrect guesses left.\n";cout << "\nYou've used the following letters:\n"<< used << endl;cout << "\nSo far, the word is:\n"<< soFar << endl;char guess;cout << "\n\nEnter your guess: ";cin >> guess;guess = toupper(guess); // make uppercase since secret word in uppercasewhile (used.find(guess) != string::npos){cout << "\nYou've already guessed " << guess << endl;cout << "Enter your guess: ";cin >> guess;guess = toupper(guess);}used += guess;if (THE_WORD.find(guess) != string::npos){cout << "That's right! " << guess << " is in the word.\n";// update soFar to include newly guessed letterfor (unsigned int i = 0; i < THE_WORD.length(); ++i){if (THE_WORD[i] == guess){soFar[i] = guess;}}}else{cout << "Sorry, " << guess << " isn't in the word.\n";++wrong;}}// shut downif (wrong == MAX_WRONG)cout << "\nYou've been hanged!";elsecout << "\nYou guessed it!";cout << "\nThe word was " << THE_WORD << endl;return 0;
}

这篇关于《C++游戏编程入门》第4章 标准模板库: Hangman的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/800788

相关文章

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

MySQL的JDBC编程详解

《MySQL的JDBC编程详解》:本文主要介绍MySQL的JDBC编程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、前置知识1. 引入依赖2. 认识 url二、JDBC 操作流程1. JDBC 的写操作2. JDBC 的读操作总结前言本文介绍了mysq

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

从入门到精通详解Python虚拟环境完全指南

《从入门到精通详解Python虚拟环境完全指南》Python虚拟环境是一个独立的Python运行环境,它允许你为不同的项目创建隔离的Python环境,下面小编就来和大家详细介绍一下吧... 目录什么是python虚拟环境一、使用venv创建和管理虚拟环境1.1 创建虚拟环境1.2 激活虚拟环境1.3 验证虚

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

AOP编程的基本概念与idea编辑器的配合体验过程

《AOP编程的基本概念与idea编辑器的配合体验过程》文章简要介绍了AOP基础概念,包括Before/Around通知、PointCut切入点、Advice通知体、JoinPoint连接点等,说明它们... 目录BeforeAroundAdvise — 通知PointCut — 切入点Acpect — 切面

C++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

C++ vector越界问题的完整解决方案

《C++vector越界问题的完整解决方案》在C++开发中,std::vector作为最常用的动态数组容器,其便捷性与性能优势使其成为处理可变长度数据的首选,然而,数组越界访问始终是威胁程序稳定性的... 目录引言一、vector越界的底层原理与危害1.1 越界访问的本质原因1.2 越界访问的实际危害二、基

Java List 使用举例(从入门到精通)

《JavaList使用举例(从入门到精通)》本文系统讲解JavaList,涵盖基础概念、核心特性、常用实现(如ArrayList、LinkedList)及性能对比,介绍创建、操作、遍历方法,结合实... 目录一、List 基础概念1.1 什么是 List?1.2 List 的核心特性1.3 List 家族成