Reputation: 13931
I have (constant) data like this:
(index) Width Height Scale Name
0 640 360 1 "SD"
1 1080 720 2 "HD"
2 1920 1080 3 "FHD"
So far - I have created structure like this:
struct Resolution
{
int Width;
int Height;
int Scale;
std::string Name;
};
Now I need an object that will let me to do something like this:
int index = 0;
int width = Resolutions[index].Width; // 360
I need enum or some array that will be constant, and accessible without initialization (static?).
Upvotes: 1
Views: 1290
Reputation: 1777
You can create a class (it's better in C++), and in your main class, a vector of this class, like that:
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;
};
And in your main class:
class MainClass {
public:
...
private:
...
std::vector<Resolution *> m_res;
};
And in the cpp file:
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));
}
You can access to an element like that (Sure, you need the getter):
this->m_res[index].getValue();
Upvotes: 2
Reputation: 42828
You need either std::vector
if the elements in Resolutions
are not compile-time-constant, or std::array
if they are and the collection doesn't need to grow. For example:
#include <array>
…
const std::array<Resolution, 3> Resolutions =
{{ /* Width Height Scale Name */
{ 640, 360, 1, "SD" },
{ 1080, 720, 2, "HD" },
{ 1920, 1080, 3, "FHD" }
}};
If you want the indices to have meaningful names instead of 0
, 1
, 2
, you can make an enum
:
enum ResolutionIndex { SD, HD, FHD };
And use it as the array index:
ResolutionIndex index = SD;
int width = Resolutions[index].Width;
This makes the code safer as you can't now do:
ResolutionIndex index = 4;
which would be an invalid index. The valid index values are hard-coded in the enum and the compiler enforces that. If you used int
:
int index = 4;
then the compiler can't help you if you give an invalid index.
Upvotes: 2
Reputation: 59997
For a start as it is constant data I would not use std::string
.
But I would do the following:
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"}
};
but on another note I would use lowercase variation for the variable.
Upvotes: 4