1

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;
}

In this example I used 4 classes of countries. 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? (E.g. 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 (e.G.: incUsa(), incCanada(), incGermany() etc.)
  3. Since I'm not really used to C++: Is this even the ideomatic approach to it? Perhaps there's a better data structructure or an alternative (and more fitting) way to result the problem.

Thanks in advance.

4

2 回答 2

7

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.

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;

etc...

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;
};
于 2013-09-07T12:31:13.307 回答
1

考虑 std::map。您可以创建一张国家地图到一张字数地图。或者一个地图字到一个国家地图来计数。是否使用枚举或字符串作为国家/地区代码取决于您。

于 2013-09-07T12:38:06.733 回答