在C ++中n = {0,1,...,n-1} [英] n={0,1,...,n-1} in C++

查看:142
本文介绍了在C ++中n = {0,1,...,n-1}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自然数n的形式定义(在集合论中)如下:

The formal definition (in set theory) of a natural number n is as follows:


  • 0是空集合

  • 1 = {0}

  • n = {0,1,...,n-1}

如果允许我这样做,我认为这会使一些C ++代码更简单:

I think this would make some C++ code much simpler, if I was allowed to do this:

for (int n : 10)
    cout << n << endl;

并打印从0到9的数字。

and it printed numbers from 0 to 9.

所以我尝试执行以下操作,但不会编译:

So I tried doing the following, which doesn't compile:

#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;
}

关于如何实现此目标的任何建议?我用c ++++收到以下错误:

Any suggestions on how to achieve this? I get the following error with clang++:

main.cpp:22:20: error: invalid range expression of type 'int'; no viable 'begin' function available
        for (int t : 10)
                ^ ~~

但我认为应该允许我这样做! :)

but I think I should be allowed to do this! :)

编辑:我知道如果我在列表中添加单词 range(或其他单词),就可以伪造它。 for循环,但我想知道是否可以不使用它。

Edit: I know I can "fake" it if I add the word "range" (or some other word) in the for loop, but I'm wondering if it's possible to do it without.

推荐答案

这是无法完成的。来自 C ++草案的6.5.4节14个标准(但C ++ 11将非常相似)

It can't be done. From section 6.5.4 of the draft of the C++ 14 standard (but C++11 will be very similar)


begin-expr end-expr 确定如下:

(1.1)-如果_ RangeT 是数组类型,[...];

(1.1) — if _RangeT is an array type, [...];

嗯,显然这不适用。 int 不是数组

Well, this one obviously doesn't apply. An int isn't an array


(1.2)—如果_RangeT是一个类类型,[...]

(1.2) — if _RangeT is a class type, [...]

不,这也不适用。


(1.3)-否则, begin-expr end-expr begin(__ range) end(__ range)分别为

哦!这看起来很有希望。您可能需要将开始 end 移到全局名称空间中,但是仍然...

Oo! This looks hopeful. You may need to move begin and end into the global namespace, but still...


其中开始
结束在关联的命名空间(3.4.2)中查找。 [注:不执行普通的不合格查找(3.4.1)
。 —尾注]

where begin and end are looked up in the associated namespaces (3.4.2). [ Note: Ordinary unqualified lookup (3.4.1) is not performed. — end note ]

(重点是我的)。烦!没有与 int 关联的名称空间。具体来说,从第3.4.2节

(emphasis mine). Bother! There aren't any namespaces associated with int. Specifically, from section 3.4.2


—如果在我们的例子中是T [ int ]是基本类型,其关联的名称空间和类的集合均为空。

— If T [int in our case] is a fundamental type, its associated sets of namespaces and classes are both empty.

唯一的解决方法是编写一个类 range 具有合适的开始和结束方法。然后,您可以编写非常Python的语言:

The only workround is to write a class range which has a suitable begin and end method. Then you could write the very pythonic:

for (int i : range(5))

这篇关于在C ++中n = {0,1,...,n-1}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆