gpt4 book ai didi

C++ unordered_map 在运行时指定类型

转载 作者:行者123 更新时间:2023-11-28 00:11:53 25 4
gpt4 key购买 nike

有什么方法可以定义 unordered_map<*,*> var 并根据情况或其他情况用适当的类型重新定义它?

我正在读取一些二进制文件,每个文件的格式都不同,因此取决于它可以通过 <int, string>, <short, string>, <int, int>, etc.. 的格式

我能想到的唯一方法就是定义它<char *, char *>但我必须定义散列和其他东西才能像那样工作。

还有其他选择吗?

编辑。为问题添加更多上下文:

我将迭代另一个列表并从 ordered_maps 中获取值,我将知道我为键使用什么类型的数据并使用它生成 JSON 字符串作为结果。

有关更多上下文,文件格式如下:

INT number of fields to use. Example: 3
-- now there is a for from 1 to 3 as we have 3 fields
CHAR type of data (1 = int8, 2 = int16, 3 = int32, 4=string)
STRING name of the field
STRING alias of the field
-- end for
-- now I do a while not EOF
-- for each field
read value from file (int8, int16, int32, string) depending the type of field
first item of the for will be the KEY
if item != first add the value to an unoredered_map using the first as key
-- end for
-- end while

最佳答案

您要在 map 中存储什么,您将如何选择它?

您的问题有两种实用的解决方案:

参数多态

这就是您首先应该尝试解决问题的方式。通过保留你的 unordered_map 的参数通用。

这主要是通过像这样的结构来完成的

class Reader {
virtual void readFile(const std::string& name) = 0;
};

template<typename K, typename V>
class RealReader {
private:
std::unordered_map<K,V> data;

public:
void readFile(const std::string& name) override {
K key = // read key;
V value = // read value
data[key] = value;
}
};

亚型多态性

定义你自己的Key和/或 Value类,以便您可以定义 std::unordered_map<Key*,Value*>然后使用您需要的类型对这些自定义类型进行子类型化。

在不知道这些将如何使用的情况下,很难说出什么是最好的。

关于C++ unordered_map 在运行时指定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32611144/

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