将用户值与枚举中的值进行比较

Compare user value with value from enum

本文关键字:比较 枚举 用户      更新时间:2023-10-16

任务的本质:根据用户的数据为用户选择最佳屏幕分辨率。 我需要用 ENUM 中的值省略用户值并返回适当的值。 例如:

enum class Resolutions {
V720_height = 720,
V720_width = 1280,
V1080_height = 1080,
V1080_width = 1920
};
int main() {
int user_height = 1200;
int user_width = 430;
// I know this does not work, just an example.
std::for_each(Resolutions.begin(), Resolutions.end(), [](Resolutions tmp) {
if (static_cast<int>(tmp) > user_height) {
std::cout << tmp << " - is better resolutionn";
}
});
}

我需要一个好主意,如何实施?

使用枚举不是最好的方法。如果您需要命名不同的分辨率,我建议您使用 std::map。

#include <map>
#include <string>
#include <iostream>
struct Resolution {
int height;
int width;
};
const std::map<std::string, Resolution> resolutions = {
{ "V720", {720, 1280} },
{ "V1080", {1080, 1920} }
};
int main() {
int user_height = 1200;
int user_width = 430;
for (auto& [key, value] : resolutions) {
if (value.height > user_height &&
value.width > user_width) {
std::cout << key << " - is better resolutionn";
}
}
}

你可以做这样的事情(注意:为了简洁起见,我使用的是 C 样式的强制转换(:

enum class Resolutions {
V720_height = 720,
V720_width = 1280,
V1080_height = 1080,
V1080_width = 1920
};
const int heights [] = { (int) Resolutions::V720_height, (int) Resolutions::V1080_height };
int main() {
int user_height = 1000;
for (auto h : heights) {
if (h > user_height) {
std::cout << h << " - is better resolutionn";
}
};
}

现场演示