【问题标题】:How to write this function used in finding a series of elements in an array?如何编写用于在数组中查找一系列元素的函数?
【发布时间】:2018-05-08 12:19:43
【问题描述】:

如何编写这个用于在数组中查找一系列元素的函数?

我编写了一个名为 find 的函数,用于查找是否在数组中的元素。现在我想用 find() 来查找一系列元素,如果所有元素都存在于这个数组中,那么函数将返回 true 或返回 false :

template <typename T>
template <typename ...Args>
bool Vector<T>::find(const Args &...args) const {
    std::deque<bool> findDeque;
    findDeque.push_back(this->find(args...));        //The statement will lead to Exception: EXC_BAD_ACCESS (code=2, address=0x...)
    auto begin {findDeque.cbegin()};
    auto end {findDeque.cend()};
    if(begin == end) {
        return false;
    }
    while(begin != end) {
        if(!*begin++) {
            return false;
        }
    }
    return true;
}

我试过了:

findDeque.push_back(this->find(args)...);

和

...
bool Vector<T>::find(Args &&...args) const {
...
findDeque.push_back(this->find(std::forward<Args>(args)...));
...

也许我研究参数包扩展不好。
我应该如何修改函数以使其成功找到。

【问题讨论】:

  • 我觉得用递归来做这件事会更清楚。现在,当您在技术上找不到其中一个时可以停止时,您会找到所有元素。如果找不到(或者你的元素用完了),使用递归并停止是我会做的。
  • 另外,你真的需要template &lt;typename ...Args&gt;吗?我假设您只能在 T 的 Vector 中找到 T 类型的其他对象
  • @Borgleader 谢谢兄弟。对于一个可变参数模板函数,在C++ Primer中提到它通常是一个递归,但是我忘记了......现在我解决了。至于template,你是对的,但我试过const T &...失败了。

标签: c++ algorithm templates variadic-templates


【解决方案1】:

您拥有无限递归,因为当您从自身调用 find() 时,您永远不会剥离一个参数。递归永远不会接近终止,最终......堆栈溢出!

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2020-02-27
  • 2019-06-08
  • 2015-08-22
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 2022-10-15
  • 2015-02-14
  • 2020-11-02
相关资源
最近更新 更多