首页 > 解决方案 > 为字母分配整数值

问题描述

是否可以将整数值分配给像“A”这样的字母?例如,如果用户输入了“A”,我想显示分配给它的值(例如,1)。我打算为字母表中的每个字母分配一个值。我发现您可以使用地图库来做到这一点,但我不想使用任何库。有没有办法只用基本的 C++ 东西来做到这一点?

标签: 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++ 标准的一部分。


推荐阅读