将用户值与枚举中的值进行比较
Compare user value with value from enum
任务的本质:根据用户的数据为用户选择最佳屏幕分辨率。 我需要用 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";
}
};
}
现场演示
相关文章:
- 不带大括号的枚举形式
- 枚举环境变量的惯用C++14/C++17方法
- 类似枚举的计算常量
- 如何正确实现和访问运算符的各种自定义枚举器
- 错误:从"int"到枚举c++的转换无效
- C++中构造函数中的枚举
- 标准::可选枚举的比较运算符
- 将用户值与枚举中的值进行比较
- 无法将返回的枚举与枚举进行比较
- 比较枚举的值会给出编译器错误
- C ++枚举可以与整数进行比较,但不能从整数分配?
- 比较枚举类值时的奇怪行为
- 为什么我没有警告枚举比较不匹配
- 将错误代码枚举与 std::error_code 进行比较
- 重新定义枚举的比较运算符
- 我是否正确地将枚举值与C++的"or"运算符进行比较?
- gtest枚举和对象之间的比较
- 将枚举与整数进行比较
- 比较枚举类型时出现逻辑错误
- 为什么我不能分配错误的枚举元素,但可以与错误的枚举元素进行比较?