【发布时间】:2018-04-11 17:30:15
【问题描述】:
自然数 n 的正式定义(在集合论中)如下:
- 0 是空集
- 1 = {0}
- n = {0,1,...,n-1}
如果允许我这样做,我认为这会使一些 C++ 代码更简单:
for (int n : 10)
cout << n << endl;
它打印了从 0 到 9 的数字。
所以我尝试执行以下操作,但无法编译:
#include <iostream>
#include <boost/iterator/counting_iterator.hpp>
boost::counting_iterator<int> begin(int t)
{
return boost::counting_iterator<int>(0);
}
boost::counting_iterator<int> end(int t)
{
return boost::counting_iterator<int>(t);
}
int main()
{
for (int t : 10)
std::cout << t << std::endl;
return 0;
}
关于如何实现这一点的任何建议?使用 clang++ 时出现以下错误:
main.cpp:22:20: error: invalid range expression of type 'int'; no viable 'begin' function available
for (int t : 10)
^ ~~
但我认为我应该被允许这样做! :)
编辑:我知道如果我在 for 循环中添加单词“范围”(或其他单词),我可以“伪造”它,但我想知道是否可以这样做没有。
【问题讨论】:
-
@mathiasfk 它使用了
begin(range_expression)和end(range_expression),所以即使不是一个好主意也应该可以。 -
std::iota可能对您有用:en.cppreference.com/w/cpp/algorithm/iota -
不过,这是一个不错的、简单的语法。也许是 C++25。
-
@tambre :更不用说将
std模板专门用于此类基本类型是未定义的行为。
标签: c++ c++14 set-theory