FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Array Operations

 
Post new topic   Reply to topic     Forum Index -> General
View previous topic :: View next topic  
Author Message
Andromeda



Joined: 06 Jul 2011
Posts: 1

PostPosted: Wed Jul 06, 2011 9:07 am    Post subject: Array Operations Reply with quote

I am quite new in D programming language. I am trying to convert my C++ classes to D that involves lots of array (vector) operations. See the below two problems. First one shows that I am required to allocate memory before assigning an array to a new array. Second shows that I cannot use an array returned by a function in arithmetic operations; it seems like the D compiler wants to see brackets [] to understand that arguments to the arithmetic operations are indeed arrays. Please write your comments on how to find better ways of dealing with these problems. Thanks.

// 1.a. This does not work
import std.stdio;

real[] getvector()
{
return [10, 20, 30];
}

void main()
{
real[] a = [5, 5, 5];
real[] c;
c[] = getvector();
writeln(c);
}

// 1.b. This works
import std.stdio;

real[] getvector()
{
return [10, 20, 30];
}

void main()
{
real[] a = [5, 5, 5];
real[] c = new real[3];
c[] = getvector();
writeln(c);
}

///////////////////////////////////////////

// 2.a. This does not work - Given this error:
// Error: invalid array operation c[] = getvector() + a[] (did you forget a [] ?)

import std.stdio;

real[] getvector()
{
return [10, 20, 30];
}

void main()
{
real[] a = [5, 5, 5];
real[] c = new real[3];
c[] = getvector() + a[];
writeln(c);
}

// 2.b. this works
import std.stdio;

real[] getvector()
{
return [10, 20, 30];
}

void main()
{
real[] a = [5, 5, 5];
real[] c = getvector();
c[] += a[];
writeln(c);
}
Back to top
View user's profile Send private message
DrakeMagi



Joined: 31 Jul 2011
Posts: 17

PostPosted: Fri Aug 12, 2011 6:01 pm    Post subject: Reply with quote

i just started learning d too.

Code:
import std.stdio;

real[] getvector()
{
   return [10,20,30];
}

void main()
{
   real[] a = [5,5,5];
   real[] c;
   c = getvector();
   
   writefln(a);
   writefln(c);
   
   c[] += a[];
   writefln(c);
}

or
Code:
c[] = getvector()[] + a[];
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic     Forum Index -> General All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group