提问者:小点点

C++17折叠语法测试向量组合


向量任意全部的标准C++17实现:

template<class C, class T>
bool contains(const C& c, const T& value) {
  return std::find(c.begin(), c.end(), value) != c.end();
}

template<class C, class... T>
bool any(const C& c, T&&... value) {
  return (... || contains(c, value));
}

template<class C, class... T>
bool all(const C& c, T&&... value) {
  return (... && contains(c, value));
}

如中所示的用法

std::array<int, 6> data0 = { 4, 6, 8, 10, 12, 14 };
assert( any(data0, 10, 55, 792));
assert( !any(data0, 11));

assert( all(data0, 6, 14, 8));
assert( !all(data0, 6, 7, 8));

是否有类似的方法来定义only,当且仅当向量的唯一值集与输入值匹配时才返回true? 因此以下断言成立

std::array<int, 6> data1 = { 1, 1, 2, 1, 2 };
assert( only(data1, 1, 2));
assert( !only(data1, 1));

共3个答案

匿名用户

您可以提供count函数:

template<class C, class T>
auto count(const C& c, const T& value) {
  return std::count(c.begin(), c.end(), value);
}

并编写,如下所示:

template<class C, class... T>
bool only(const C& c, T&&... value) {
  return (count(c, value) + ...) == c.size();
}

这会处理c中的重复元素,但要求s是唯一的。

这是一个演示。

匿名用户

template<class C, class...Ts>
bool only( C const& c, Ts&&...ts ) {
  std::size_t count = (std::size_t(0) + ... + contains(c, ts));
  return count == c.size();
}

这将计算Ts...列表中有多少个C,如果您找到的数字等于C的元素,则返回true。 现在假设cts具有唯一性。

我们只需将计数移到only中,并在std算法中进行测试:

template<class C, class...Ts>
bool only( C const& c, Ts&&...ts ) {
  using std::begin; using std::end;
  auto count = std::count_if( begin(c), end(c), [&](auto&& elem) {
    return ((elem == ts) || ...);
  } );
  return count == c.size();
}

鲍勃是你叔叔。

我们也可以执行基于notcontainsonly算法,但我认为这要复杂得多。

匿名用户

它不使用折叠表达式,但应该可以工作

template<class C, class... T>
bool only(const C& c, T&& ...vals) {
    auto ilist = {vals...}; //create initializer_list

    for (auto el : c) {
        if (!contains(ilist, el)) return false;
    }
    return true;
}

使用折叠表达式而不是std::initializer_list的东西

template<class T, class... Ts>
bool is_one_of(const T& val, Ts&& ...vals)
{
    return ((val == vals) || ...);
}

template<class C, class... Ts>
bool only(const C& c, Ts&& ...vals)
{
    for (const auto& el : c) {
        if (!is_one_of(el, vals...)) return false;
    }
    return true;
}

// or if you hate raw loops
template<class C, class... Ts>
bool only(const C& c, Ts&& ...vals)
{
    using std::beign; using std::end;
    auto it = std::find_if(begin(c), end(c), [&](const auto& el) {
        return !is_one_of(el, vals...);
    });
    return (it == end(c));
}

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++17|折叠|语法|测试|向量|组合)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?