1

有些人的自定义列表类带有car(例如头部)cdr(例如尾部)。我想知道是否std::list可以用来支持这些操作。 car是微不足道的。但我不知道如何cdr模仿。

4

1 回答 1

3

在 C++20 中,我们得到了 Ranges 库。我还没有详细研究它,但我怀疑子范围或视图可能会有所帮助。

预 C++20

在 C++ 中(直到现在),我们通常不直接传递一个列表(或其他容器),而是传递一对迭代器。看看这个<algorithm>库:像std::sort这样的函数不引用容器——相反,它们接受一个first迭代器和一个last迭代器。

重要提示:last不指向最后一项,而是指向它之外的一个地方 - 与给你的一样std::list::end()。这意味着当first == last您有“一个空列表”时

在 C++20 之前的世界中,您通常会以相同的方式编写代码。这样做的一个好处是,如果你有一对迭代器firstand last,那么(只要 first != last*firstcar,并且这对std::next(first)lastcdr。所以:

(defun sum (list)
  (if (null list)
      0
    (+ (car list) (sum (cdr list)))))

变成类似的东西

template <class ForwardIter>
int sum(ForwardIter first, ForwardIter last) {
  return (first == last)
           ? 0
           : (*first) + sum(std::next(first), last);
}

(我知道有些人会不同意我如何在多行上格式化该条件运算符 - 但我想反映 Lisp 风格。)

于 2020-04-20T23:37:04.707 回答