在我的程序中,我得到一个字符串,它由属性名称和属性值组成。例如:string X 2
。我的问题是,我有很多属性,他们有不同的类型。它可以是int,boolean或枚举。例如,X 2
应为int x = 2;
STATUS 0
应为bool status = false
,依此类推。
所以我需要读取字符串并使用取决于字符串的值创建属性。我考虑过hash_map,但也许你有另一个想法?
我也不知道如何将属性的类型放在hash_map中。 像这样:
typedef unordered_map<string, type> MapType;
我知道hash_map如何与函数指针一起工作;也许有类型的东西。这可以给我一个参考,例如,int,bool,而不是我可以搜索地图并从我的字符串中转换值。
答案 0 :(得分:1)
在从字符串加载/读取属性时,可以使用map<string, string>
类型来存储属性,例如“X 2”或“STATUS 0”。接下来,写一个例如AttributesContainer充当地图的包装器,方法为getString(string key)
,getInt(string key)
和getBoolean(string key)
等。
因此,根据调用者和调用的get方法,您可以根据首选逻辑解释映射中的值。如果调用getBoolean,您可以自由地将0/1解释为boolean,但如果调用getInt,则返回int 0或1。
答案 1 :(得分:0)
从配置文件中获取不同类型的值(布尔值,整数,字符串......)是一个已经解决过很多次的问题......可能太多次了:)
的完成情况答案 2 :(得分:0)
这可以使用 Factory 模式完成,但您需要有一个派生的根类。例如,工厂如何返回指向string
的指针或指向bool
的指针?
这些物品是如何使用的?
另一个建议是为每种类型的对象和两个vector
容器提供std::map
,一个用于创建对象的函数,另一个用于创建函数的函数指针。
使用其中一个贴图获取创建项目的功能。
使用其他地图获取项目的向量。
通过传递正确的向量来执行该函数。
否则,它指向void
。
答案 3 :(得分:0)
也许您需要查看一些c ++ JSON library (parser)来解决您的问题。
答案 4 :(得分:0)
我无法相信我即将提出这个建议,但这里有......
定义一个简单的attribute
类,它是std::string
的包装 - 这是你的价值。这个类应该提供转换操作符(尽管我不喜欢它们,在这种情况下,它们可以让生活变得更容易)。
#include <iostream>
#include <boost/lexical_cast.hpp>
struct attribute
{
std::string value;
operator bool() const { return boost::lexical_cast<bool>(value); }
operator int() const { return boost::lexical_cast<int>(value); }
operator unsigned int() const { return boost::lexical_cast<unsigned int>(value); }
operator double() const { return boost::lexical_cast<double>(value); }
operator std::string() const { return value; }
};
int main(void)
{
attribute a = { "foo" };
attribute b = { "10" };
std::string sa = a;
int sb = b;
unsigned int su = b;
std::cout << sa << std::endl;
std::cout << sb << std::endl;
std::cout << su << std::endl;
}
所以在这里,您要分配的变量类型决定了所应用的转换。现在使用这种方法的主要问题是,如果没有直接转换运算符,编译器将选择最佳匹配 - 这可能并不总是您想要的。为了安全起见,定义您需要的所有转换,您可能没问题。
接下来,将此attribute
与字符串键一起存储在地图中(注意:您必须实现默认的ctor / copy ctor / assign op等,因为默认值不安全)。如果您不能被后者困扰,请在地图中存储智能指针,例如
std::map<std::string, boost::shared_ptr<attribute> > attributes;
现在您的界面应该接受一个键并返回attribute
,例如
attribute const& get(std::string const& some_key)
{
map<>::iterator it = attributes.find(some_key);
return *it->second;
}
bool bv = get(some_key); // automatically converted to bool (if lexical_cast doesn't throw)