gpt4 book ai didi

c++ - 实现字符串到整数查找表的快速且可维护的方法

转载 作者:行者123 更新时间:2023-11-28 01:15:17 24 4
gpt4 key购买 nike

我可以找到很多关于如何将整数映射到字符串常量的问题,并且有明显的解决方案

char const* strings[] = {"Foo", "Bar", ...};

现在,假设我想要反转:我有字符串“Bar”,并且想要 1。我的字符串最多 4 个字符,ascii null 不是有效值。有 64 个整数可以将值映射到。我是否必须编写带有字符串比较的长 if-else 结构,还是有更好的方法。

澄清一下,我更喜欢不需要运行时初始化的解决方案,从 C++17 开始,这使得 ti 无法使用 std::mapstd::unordered_map.

最佳答案

My strings are up to 4 characters and ascii null is not a valid value.

有了这个条件,您可以将字符串转换为整数,并使用您最喜欢的编译时整数到整数映射。

例如,使用开关:

#include <cstddef>
#include <cstdint>

namespace detail {
constexpr std::uint64_t string_as_int(const char* string) noexcept {
std::uint64_t result = 0;
std::uint64_t i = 0;
for (; i < 4 && *string; ++string, ++i) {
result |= static_cast<std::uint64_t>(static_cast<unsigned char>(*string)) << (i * 8u);
}
return result;
}

constexpr std::uint64_t operator ""_h(const char* string, std::size_t) noexcept {
return string_as_int(string);
}
}

constexpr int lookup(const char* string) {
using detail::operator ""_h;
switch (detail::string_as_int(string)) {
case "Foo"_h: return 1;
case "Bar"_h: return 2;
default: return 0;
}
}

关于c++ - 实现字符串到整数查找表的快速且可维护的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58902217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com