我有(常量)数据,如下所示:
int index = 0;
int width = Resolutions[index].Width; // 360
到目前为止 - 我已经创建了这样的结构:
{{1}}
现在我需要一个让我做这样的事情的对象:
{{1}}
我需要枚举或一些不变的数组(静态?)。
答案 0 :(得分:4)
首先,因为它是常量数据,所以我不会使用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"}
};
但另一方面,我会对变量使用小写变体。
答案 1 :(得分:2)
如果std::vector
中的元素不是编译时常量,则需要Resolutions
,如果它们是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" }
}};
。例如:
0
如果您希望索引具有有意义的名称而不是1
,2
,enum
,则可以创建enum ResolutionIndex { SD, HD, FHD };
:
ResolutionIndex index = SD;
int width = Resolutions[index].Width;
并将其用作数组索引:
ResolutionIndex index = 4;
这使得代码更安全,因为您现在无法做到:
int
这将是一个无效的索引。有效的索引值在枚举中进行了硬编码,编译器强制执行该操作。如果您使用int index = 4;
:
if ( have_rows( 'repeater_field', $homepage_id ) ) {
$i = 0;
// loop through the rows of data
while ( have_rows( 'repeater_field', $homepage_id ) ) {
the_row();
//Get imgs
$imgs[$i]['img_test'] = get_sub_field( 'img_test' );
$i++;
}
}
echo "src = ".$imgs[0]['img_test']["sizes"]["medium"];
如果您提供无效索引,编译器就无法帮助您。
答案 2 :(得分:2)
你可以创建一个类(它在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();