我正在阅读一篇关于 C++ 概念(也就是 C++20)的(打印版,德文)文章。
这篇文章给出了一个函数模板的例子,使用Sortable
理念:
template<typename Cont>
requires Sortable<Cont>()
void sort(Cont& container) { ... }
它声称编译器会拒绝以下代码:
std::list<int> lst = { 1, 7, 5, 12 };
sort(lst);
错误如下:
ERROR: lst is not random-access container with <
假设这篇文章是正确的 - 为什么 list 的 int 值是不可排序的?对我来说,在考虑“可排序”的东西时,整数列表就像典型的例子?!
不,我不是在问 std::sort。我在问:为什么 概念 Sortable 不适用于 std::list<int>
?
最佳答案
And no, I am not asking about std::sort. I am asking: why does the concept Sortable not work for a std::list?
好吧,这完全取决于如何您定义可排序 概念。因此,在您正在阅读的文本的上下文中,可能假设 Sortable 容器必须在随机访问迭代器上运行——例如 std::sort
采用一对随机访问迭代器;它不能对容器元素进行排序,比如 std::list
,它不支持随机访问迭代器。
但是,这不意味着您不能定义自己的概念,例如FlexySortable(连同算法flexy_sort
)在 non-random-access-iterator 上也是如此。文本只是给出一个概念的例子来解释关于概念如何帮助您表达您的意图和假设的一般想法直接在编译器可以通过执行谓词(即概念)来验证的代码中。
关于c++ - 为什么 std::list<int> 不可排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47442992/