【问题标题】:Enum or array with structs inside枚举或数组,里面有结构
【发布时间】:2015-07-11 00:17:06
【问题描述】:

我有这样的(恒定的)数据:

(index)  Width  Height  Scale  Name
     0    640      360      1   "SD"
     1   1080      720      2   "HD"
     2   1920     1080      3  "FHD"

到目前为止 - 我已经创建了这样的结构:

struct Resolution
{
    int Width;
    int Height;
    int Scale;
    std::string Name;
};

现在我需要一个可以让我执行以下操作的对象:

int index = 0;
int width = Resolutions[index].Width; // 360

我需要枚举或一些不变的数组,无需初始化即可访问(静态?)。

【问题讨论】:

  • 我不明白,你在哪里需要枚举?
  • 嗯...我想增加索引。我不确定我是否需要枚举。它可能是一些数组。

标签: c++ arrays struct enums


【解决方案1】:

首先,因为它是常量数据,我不会使用std::string

但我会做以下事情:

struct Resolution
{
    int Width;
    int Height;
    int Scale;
    const char * Name;
};


struct Resolution Resolutions[] = {

      {640, 360, 1, "SD"},
      { 1080, 720, 2, "HD"},
      { 1920, 1080, 3, "FHD"}
    };

但另一方面,我会为变量使用小写变体。

【讨论】:

  • 为什么不std::string
  • @Kamil 如果你误用了const,编译器通常会发出一个错误,所以只要你可以使用它,只要它有意义。 使用const比使用它有更多的负面影响。
  • 定义数组时也可以省略struct关键字。
  • @zenith 没有实现在文件范围内将堆栈用于字符串
  • 这里是使用const char *还是std::string可能取决于你最常用的用法;例如,如果您只将字符串传递给期望 const std::string & 的函数,那么如果您使用 const char *,那么每次此类调用都会浪费时间构建临时对象。
【解决方案2】:

如果Resolutions 中的元素不是编译时间常数,则需要std::vector,或者如果它们是并且集合不需要增长,则需要std::array。例如:

#include <array>
…

const std::array<Resolution, 3> Resolutions =
{{ /* Width  Height  Scale  Name */
    {  640,     360,     1,  "SD" },
    { 1080,     720,     2,  "HD" },
    { 1920,    1080,     3, "FHD" }
}};

如果您希望索引具有有意义的名称而不是 012,您可以创建一个 enum

enum ResolutionIndex { SD, HD, FHD };

并将其用作数组索引:

ResolutionIndex index = SD;
int width = Resolutions[index].Width;

这使代码更安全,而您现在无法做到:

ResolutionIndex index = 4;

这将是一个无效的索引。有效的索引值在枚举中是硬编码的,编译器会强制执行。如果你使用int

int index = 4;

如果你给出一个无效的索引,编译器将无法帮助你。

【讨论】:

  • 或者,如果你没有使用 C++11(或者只是不想使用std::array):const Resolution Resolutions[3] = {...};
  • 当它保持不变时,为什么要把它放在堆上(包括所有的构造等)?
  • @EdHeal std::array 在堆栈上分配。
  • 我阅读了这个答案的矢量版本。 BTW std:::string 在堆上
  • @EdHeal 如果它是小字符串优化,则不是,因为它可能是。
【解决方案3】:

您可以创建一个类(在 C++ 中更好),并在您的主类中创建此类的向量,如下所示:

class Resolution {
public:
      Resolution(unsigned int, unsigned int, unsigned int, std::string const &);
      ~Resolution();

private:
      unsigned int Width;
      unsigned int Height;
      unsigned int Scale;
      std::string  Name;
};

在你的主课中:

class MainClass {
public:
      ...
private:
      ...
      std::vector<Resolution *> m_res;
};

在cpp文件中:

MainClass::MainClass() {
           this->m_res.push_back(new Resolution(640, 360, 1, SD));
           this->m_res.push_back(new Resolution(1080, 720, 2, HD));
           this->m_res.push_back(new Resolution(1920, 1080, 3, FHD));
}

您可以访问这样的元素(当然,您需要 getter):

this->m_res[index].getValue();

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 2016-11-29
    • 2019-03-02
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多