c++ - 为字母分配整数值
问题描述
是否可以将整数值分配给像“A”这样的字母?例如,如果用户输入了“A”,我想显示分配给它的值(例如,1)。我打算为字母表中的每个字母分配一个值。我发现您可以使用地图库来做到这一点,但我不想使用任何库。有没有办法只用基本的 C++ 东西来做到这一点?
解决方案
一种非常简单的方法是通过索引关联一个简单的原始数组:
char char_num_slots[] = { '\0' /* associates to index 0 */
, 'A' /* associates to index 1 */
, 'C' /* associates to index 2 */
, 'K' /* associates to index 3 */
// aso ...
};
使用 c++ 的自然方法是使用 astd::map<char,int>
虽然:
std::map<char,int> char_num_slots = { { 'A', 1 }
, { 'C', 42 }
, { 'K', 512 }
// aso ...
};
我认为很明显上述方法的区别在哪里,以及如何使用std::map
是优越的。
有没有办法只用基本的 C++ 东西来做到这一点?
是的,使用std::map
计数作为 c++基本内容并且是 c++ 标准的一部分。
推荐阅读
- spring-boot - Hazelcast 节点无法启动
- java - 当我使用junit 5时发现使用了未声明的依赖项junit 4.13
- amazon-ec2 - 在主机文件 Ansible 中存储多个 ec2 实例详细信息?
- wpf - 使用 OpacityMask 和 CombinedGeometry 自定义轨道的 WPF 滑块
- node.js - 在 React.js 项目上安装 npm 时出错
- sql - 如何在 SQL Server 中找到任期?
- c# - 是否有一个属性或编译器标志来消除对泛型接口的扩展方法指定类型约束的需要?
- html - Angular 如何在 mat-icon 上添加文本
- mongodb - Next.js API 和数据库连接问题
- bash - 使用 psql 命令时 shellscript 出错