初始化一个数组的成员没有一个循环
我有一个.NET C#工作面试,其中一个问题是“初始化整数数组1,2,3,没有循环,没有递归和没有初始化作为初始化一个数组的成员没有一个循环
int[] arr = new [] {1, 2, 3, ...100};
是否有可能
一行代码:?
Enumerable.Range(1,100).ToArray();
我在术语方面有点差,所以如果我在说一些白痴,请原谅我:这是一个初始化,还是只做一项任务? –
它返回一个数组,你需要分配给你的变量 – cokceken
@MatteoUmili当然,为什么不呢?你当然可以把'int [] array ='放在它的前面,使它更加明显。 –
C++解决方案(对不起,从来没有在床上,用C#) - 一些其他操作的副作用
struct foo {
static std::vector<int> bar;
// constructor
foo() {
bar.push_back(bar.size());
}
};
// C++ style of initialization of class/static variables
std::vector<int> foo::bar;
int main() {
do {
foo x[100]; // this initializes the foo::bar, goes out of scope and the memory
// is freed, but the side effects persist
} while(false);
std::cout << foo::bar.size() << std::endl; // yeap, 100
int* myArray=foo::bar.data();
//^
// +--- use it before I change my mind and do...
foo::bar.clear();
foo y[200];
}
在'C#'中,当你执行'foo x [100];'时,元素不会被默认的构造函数自动初始化,所以你将拥有一个包含100个空元素的数组。 (并且没有副作用)。仍+1,因为我喜欢这个想法 –
@MatteoUmili即使你分配结构(值)而不是引用?我不知道C#足够,但是[我正在读的其他内容](http://*.com/a/29669763/620908)。 (是的,我知道,这个技巧不会像Java那样工作,因为所有对象都是通过引用的方式) –
在C#中'Structs'不能包含显式无参数构造函数([CS0568](https://msdn.microsoft.com/) .com/en-us/library/x2xcf8ft.aspx)) –
C#的解决方案 - 而不是一个循环,没有递归,未初始化因为如此,休息一会...一个伟大的方法使用事件由框架/ OS提供排队 - 当然,人们永远不会使用类似这在练习,但它是服从信的要求(我会谈论精神juuust稍后)。此外,可能会移植到多种语言,包括javascript(请参阅setinterval)。现在
,原谅我一会儿,我需要卸载单(并采取了一些强有力的精神或两杆拿到过创伤):
using System;
using System.Timers;
using System.Threading;
namespace foo
{
class MainClass
{
public static void Main (string[] args)
{
int[] a=new int[100];
a [99] = 0;
int count = 0;
System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Interval = 36000; // so that we can have a beer by the time we have our array
tmr.Elapsed += async (sender, e) =>
{ if(count<a.Length) a[count]=count++; }
;
tmr.Start();
while (a [99] < 99) {
Thread.Sleep (10);
}
foreach(int i in a) {
Console.WriteLine (i);
}
}
}
}
如果你在一次采访中写到这件事,而你被雇用而不是从房间里笑出来,那么公司就不是你想要的工作。世界上没有足够的精神让你通过你最初的代码库浏览。 –
@CodyGray“公司不是你想要工作的公司”这个简单的OP问题是一个足够的标志,我不想为他们工作。对于一个愚蠢的问题,一个愚蠢的答案是最好的答案。 –
'诠释ARR [] =新INT [ 100]; arr [0] = 1; arr [1] = 2; arr [2] = 3' ..... –
这听起来像一个可怕的面试问题,肯定他们会希望你用循环... – TheLethalCoder
@TheLethalCoder下一关:你可以用只有你的手肘编写一个C编译器。 –