[英]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: 我对此的疑问如下:
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 ++中,
class
和struct
定义是在编译时静态创建的,因此,例如,您不能在运行时将新成员添加到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.