简体   繁体   English

C ++中的动态结构

[英]Dynamic Structs in C++

For a project in C++ (I'm relatively new to this language) I want to create a structure which stores a given word and a count for multiple classes. 对于使用C ++的项目(我是这种语言的新手),我想创建一个存储给定单词和多个类计数的结构。 Eg: 例如:

struct Word
{
  string word;

  int usaCount     = 0;
  int canadaCount  = 0;
  int germanyCount = 0;
  int ukCount      = 0;
}

In this example I used 4 classes of countries. 在此示例中,我使用了4类国家。 In fact there are hundreds of country classes. 实际上,有数百种国家/地区类别。

My questions regarding this are the following: 我对此的疑问如下:

  1. Is there any way to generate this list of countries dynamically? 有什么方法可以动态生成此国家列表? (Eg there is a file of countries which is read and on that basis this struct is generated) (例如,有一个读取的国家/地区文件,并在此基础上生成此结构)
  2. Fitting for this struct should be a function which increments the count if the class is seen. 适合该结构的函数应该是可以在看到类时增加计数的函数。 Is there also a way to make this "dynamic" by which I mean that I want to avoid one function per class (eG: incUsa(), incCanada(), incGermany() etc.) 还有一种使这种“动态的”方法的意思是,我要避免每个类使用一个函数(例如,incUsa(),incCanada(),incGermany()等)。
  3. Since I'm not really used to C++: Is this even the ideomatic approach to it? 由于我并不真正习惯C ++:这甚至是它的意识形态方法吗? Perhaps there's a better data structructure or an alternative (and more fitting) way to result the problem. 也许有更好的数据结构或替代(更合适)的方式来解决问题。

Thanks in advance. 提前致谢。

In C++ class and struct definitions are statically created at compile time, so you can't, for example, add a new member to a struct at runtime. 在C ++中, classstruct定义是在编译时静态创建的,因此,例如,您不能在运行时将新成员添加到struct中。

For a dynamic data structure, you can use an associative container like std::map : 对于动态数据结构,可以使用诸如std::map类的关联容器:

std::map<std::string, int> count_map;
count_map["usa"] = 1;
count_map["uk"] = 2;

etc... 等等...

You can include count_map as a member in the definition of your struct Word : 您可以将count_map作为成员包含在struct Word的定义中:

struct Word
{
  std::string word;
  std::map<std::string, int> count_map;
};

Consider std::map. 考虑std :: map。 You could create a map of countries to a map of words to counts. 您可以创建国家地图,也可以创建字数地图。 Or a map words to a map of countries to counts. 或将地图字词映射到要计数的国家/地区地图。 Whether you use an enum or strings for your country codes is up to you. 是否使用枚举或字符串作为国家/地区代码取决于您自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM