带有 std::map 的 c++ 结构是拥有动态数据对象的好设计吗?

Is a c++ struct with std::map's a good design to have a dynamic data object?

本文关键字:对象 数据 拥有 map std c++ 结构 带有 动态      更新时间:2023-10-16

问题归结为:在 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>stringmap,而不是每个支持的值类型的容器,但基本上是的,这看起来不错。