C++ 中的动态结构 [英] Dynamic Structs in C++
问题描述
对于 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. E.g.:
struct Word
{
string word;
int usaCount = 0;
int canadaCount = 0;
int germanyCount = 0;
int ukCount = 0;
}
在这个例子中,我使用了 4 类国家.事实上,有数百个国家课程.
In this example I used 4 classes of countries. In fact there are hundreds of country classes.
我的问题如下:
- 有没有办法动态生成这个国家列表?(例如,有一个国家文件被读取,并在此基础上生成此结构)
- 拟合这个结构应该是一个函数,如果看到类,它会增加计数.是否还有一种方法可以使这种动态"变得动态",我的意思是我想避免每个类使用一个函数(例如:incUsa()、incCanada()、incGermany() 等)
- 因为我并不真正习惯 C++:这甚至是意识形态的方法吗?也许有更好的数据结构或替代(且更合适)的方法来导致问题.
提前致谢.
推荐答案
在 C++ 中 class
和 struct
定义是在编译时静态创建的,所以你不能,例如,在运行时向 struct
添加一个新成员.
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.
对于动态数据结构,您可以使用关联容器,例如 std::map
:
For a dynamic data structure, you can use an associative container like std::map
:
std::map<std::string, int> count_map;
count_map["usa"] = 1;
count_map["uk"] = 2;
等等...
您可以将 count_map
作为成员包含在 struct Word
的定义中:
You can include count_map
as a member in the definition of your struct Word
:
struct Word
{
std::string word;
std::map<std::string, int> count_map;
};
这篇关于C++ 中的动态结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!