3 回答

TA貢獻1865條經驗 獲得超7個贊
如果要檢查的值足夠小,則可以為要查找的值創建一個位掩碼,然后檢查要設置的位。
假設您關心幾個小組。
static const unsigned values_group_1 = (1 << 1) | (1 << 2) | (1 << 3);
static const unsigned values_group_2 = (1 << 4) | (1 << 5) | (1 << 6);
static const unsigned values_group_3 = (1 << 7) | (1 << 8) | (1 << 9);
if ((1 << value_to_check) & values_group_1) {
// You found a match for group 1
}
if ((1 << value_to_check) & values_group_2) {
// You found a match for group 2
}
if ((1 << value_to_check) & values_group_3) {
// You found a match for group 3
}
這種方法最適合于不超過CPU喜歡使用的自然大小的值。在現代通常為64,但是可能會因環境的不同而有所不同。

TA貢獻1827條經驗 獲得超9個贊
這是C ++ 11中的一種使用方法std::initializer_list:
#include <algorithm>
#include <initializer_list>
template <typename T>
bool is_in(const T& v, std::initializer_list<T> lst)
{
return std::find(std::begin(lst), std::end(lst), v) != std::end(lst);
}
這樣,您可以執行以下操作:
if (is_in(num, {1, 2, 3})) { DO STUFF }
但是,當不與內置類型一起使用時,效率不是很高。int可以正常工作,但是std::string例如,如果您比較變量,則生成的代碼簡直糟透了。
但是,在C ++ 17中,您可以改用效率更高的解決方案,該解決方案適用于任何類型:
template<typename First, typename ... T>
bool is_in(First &&first, T && ... t)
{
return ((first == t) || ...);
}
// ...
// s1, s2, s3, s4 are strings.
if (is_in(s1, s2, s3, s4)) // ...
在C ++ 11版本將是非常低效的位置,而這個版本應該產生相同的代碼手寫比較。
- 3 回答
- 0 關注
- 761 瀏覽
添加回答
舉報