【问题标题】:Static assertion if one std::array is a subset of the other一个 std::array 是另一个的子集的静态断言
【发布时间】:2022-11-28 00:29:47
【问题描述】:

我正在使用两个 constexpr std::array:

constexpr std::array full = { 1,2,3 };
constexpr std::array subset = { 3 };

如果第二个是第一个的子集,我想静态断言。

在上面的例子中,断言应该成功,而在下面的例子中,它应该失败:

constexpr std::array full = { 1,2,3 };
constexpr std::array subset = { 3, 4 };

我写了一个有效的 constexpr 函数:

constexpr bool isSubset(decltype(full)& a, decltype(subset)& b)
{
    for (const auto& subsetElement : b) {
        bool found = false;
        for (const auto& fullElement : a) {
            if (subsetElement == fullElement) {
                found = true;
                break;
            }
        }
        if (!found) {
            return false;
        }
    }
    return true;
}

但我想知道是否有另一种更直接(没有 decltype,也许没有 constexpr 函数?)的方法(最新的 CPP)。

【问题讨论】:

标签: c++ constexpr constexpr-function


【解决方案1】:

你可以使用std::includes:

如果排序范围 [first2, last2) 是排序范围 [first1, last1) 的子序列,则返回 true。

Demo:

constexpr auto is_subset = 
    (std::includes(full.begin(), full.end(), subset.begin(), subset.end()));

static_assert(is_subset, "Has to be a subset");

【讨论】:

    猜你喜欢
    • 2013-06-27
    • 1970-01-01
    • 2014-10-21
    • 2020-03-16
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多