带有 std::map 的 c++ 结构是拥有动态数据对象的好设计吗?
Is a c++ struct with std::map's a good design to have a dynamic data object?
问题归结为:在 c++ 中拥有一个结构体,它包含一些std::map
,如容器,用于动态地向某个对象添加信息/属性,这是好的设计吗?
在我的例子中,对象(参见下面的代码片段)是由各种优化器返回的FitResult
(优化模型的一组参数,以最好地描述给定的数据集)。
该FitResult
包含以下信息:
- 描述数据集的最佳参数集
- 有关这些参数的错误信息
- 有关优化过程和收敛的信息
- 等
在我看来,这个FitResult
对象只是数据,不需要任何功能。因此,我会将其保留为结构体,没有函数。由于存储在对象中的信息(如我上面列出的)可能会因您使用的优化器而异,因此我希望保持FitResult
的内容动态。为了以后有一个简单的方法来访问信息,我决定使用像容器这样的键值。映射的键不必是std::string
的,我想改用类枚举来避免拼写错误。
你认为这是一个好的选择,还是会走一条不同的道路,比如基类?
struct FitResult {
// these properties are separate members, since they are always given
ParameterList InitialParameters;
ParameterList FinalParameters;
double InitialEstimatorValue = 0.0;
double FinalEstimatorValue = 0.0;
double ElapsedTimeInSeconds = 0.0;
/// optional properties
std::map<std::string, double> DoubleProperties;
std::map<std::string, int> IntProperties;
std::map<std::string, ParameterList> ParameterListProperties;
std::map<std::string, std::vector<double>> DoubleListProperties;
std::map<std::string, std::vector<std::vector<double>>>
MatrixProperties;
}
编辑:
我的问题措辞不太好。我应该提到,就我而言,我不需要具有将属性动态添加到FitResult
的功能。只是不同的Optimizer
类需要不同的属性集来添加到FitResult
中。不同Optimizers
的属性会有所不同,但否则会保持固定。 但是,我不想使用继承将更多成员字段添加到FitResult
类,而是使用这种动态结构方法。您会推荐这两种解决方案中的哪一种?
我会考虑variant<things you need>
string
的map
,而不是每个支持的值类型的容器,但基本上是的,这看起来不错。
相关文章:
- 使用指针访问数组中的对象数据成员
- 如果在 C++ 构造函数中以错误的顺序初始化对象数据,会发生什么类型的错误
- 只需调用对象即可获取对象数据
- 从R中访问C 对象数据成员
- C 如何将对象数据传递到用户定义的转换操作员中
- 通用B树,用于存储自定义对象/数据类型
- 通过指向对象数据成员的指针更改该对象的值
- C .更改对象数据成员的数据成员
- 排序类对象数据成员从大到小
- 从程序集中调用的C++方法返回对象数据
- 如何设置对象数据成员与这个c++与这个
- 访问私有对象数据时出现问题
- 流操作,用于以不同格式输出对象数据
- 更新标准::映射对象数据
- C++是保证在基本对象std::swap之后有效的派生对象数据
- 添加类的对象数据
- 将对象/数据从库传递到控制台应用程序(如何)
- 将一个对象数据复制到另一个相同类型 C++ 的对象
- 用c++将对象数据写入txt文件
- c++继承.更改对象数据类型