Skip to content

Commit

Permalink
[faq] 补充具名要求迭代器和概念迭代器
Browse files Browse the repository at this point in the history
  • Loading branch information
FeignClaims committed Feb 5, 2024
1 parent 7f5ebf1 commit 0483da0
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions docs/faq/range_iterator_and_algorithm/main.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1239,14 +1239,34 @@ TODO, 没想到好的解释.

在 C++20 以前, 标准库即通过标签分发或其他各种方式实现 STL 算法.

.. code-block:: cpp
:linenos:
class Iter {
public:
using iterator_category = bidirectional_iterator_tag;
};
对应的迭代器层次由 :cpp:`std::iterator_traits<Iter>::iterator_category` 得到:

.. code-block:: cpp
:linenos:
template <typename Iter, typename T>
Iter find_last(Iter begin, Iter end, T const& value) {
return find_last_impl(begin, end,
value,
std::iterator_traits<Iter>::iterator_category());
}
------------------------------------------------------------------------------------------------------------------------
概念
------------------------------------------------------------------------------------------------------------------------

经过二十几年的设计权衡, C++20 正式引入了概念 (concepts), 这让算法定义非常容易:

.. code-block:: cpp
:emphasize-lines: 4, 10
:emphasize-lines: 5, 11
:linenos:
#include <iterator>
Expand All @@ -1262,4 +1282,16 @@ TODO, 没想到好的解释.
requires std::forward_iterator<Iter>
Iter find_last(Iter begin, Iter end, T const& value) {
/* ... */
}
}
------------------------------------------------------------------------------------------------------------------------
迭代器层次的定义
------------------------------------------------------------------------------------------------------------------------

C++17 及以前, C++ 标准用文字描述了这些迭代器概念的 `具名要求 <https://zh.cppreference.com/w/cpp/iterator>`_.

.. margin::

例如原来要求 :cpp:`begin` 和 :cpp:`end` 必须是同一类型, 而现在针对范围不再作这样的强制要求.

C++20 及以后, 不同层次的迭代器便直接定义为 :cpp:`代码可用的概念 <https://zh.cppreference.com/w/cpp/iterator#.E8.BF.AD.E4.BB.A3.E5.99.A8.E6.A6.82.E5.BF.B5_.28C.2B.2B20_.E8.B5.B7.29>`, 并进行了一些调整; 而原来的具名要求称为 `Cpp17Iterator <https://eel.is/c++draft/iterator.cpp17>`_ 或 `LegacyIterator <https://zh.cppreference.com/w/cpp/iterator>`_.

0 comments on commit 0483da0

Please sign in to comment.