Why function template 'among' is of complexity O(1) and not O(n)?
anonymous
anonymous at example.com
Wed Feb 19 13:52:05 PST 2014
On Wednesday, 19 February 2014 at 19:45:39 UTC, Ali Çehreli wrote:
> On 02/19/2014 01:46 AM, Gopan wrote:
[...]
> > uint among(T, Us...)(T v, Us vals)
> > {
> > foreach (i, U; Us)
> > {
> > writeln("checking ", v, " == ", vals[i]);
> > if (v == vals[i])
> > return i + 1;
> > }
> > return 0;
> > }
[...]
> You get that output only because you have inserted the
> writeln() expressions in there.
>
> That foreach over variadic template arguments is a
> "compile-time foreach"[1]. For example, if v were 2 and vals
> were "1, 2, 3", the original code would be expanded to the
> following:
>
> if (2 == 1) return 1; // i == 0
> if (2 == 2) return 2; // i == 1
> if (2 == 3) return 3; // i == 3
>
> Since all of those conditions is known to be true or false at
> compile time, the compiler will reduce the code to the
> following:
>
> return 2;
>
> Ali
>
> [1] http://ddili.org/ders/d.en/tuples.html
Nope. v and vals are runtime parameters, their values are not
known at compile time. What's known at compile time is
vals.length.
More information about the Digitalmars-d-learn
mailing list