Sign in to follow this  
Misery

How to assign a multiple entries in array using [ ] and = operators

Recommended Posts

Misery    354
Hi there,

I have a following problem: I would like to make an array template in C++ that would have similar operator like one in Scilab/Matlab:
[code]
Array[range] = scalar;
[/code]

This expression would cause all elements of Array listed in range, take value of scalar. How do I do that?

[code]

class FloatArray
{
public:
float Elements[100];

//how do I define operator
??? operator [ ] (int *Range)
{ }

//and operator
???? operator = (???)
{ }
};
[/code]

To obtain this?

Regards,
Misery

Share this post


Link to post
Share on other sites
Hodgman    51323
Something along the lines of this code (untested), which returns a proxy object to perform the assignment should work:[code]struct Range
{
int begin, end;
};

class FloatRangeProxy
{
float* begin;
float* end;
public:
FloatRangeProxy( float* b, float* e ) : begin(b), end(e) {}

const float operator=( float f )
{
for( float* i=begin; i!=end; ++i )
*i = f;
return f;
}
};

class FloatArray
{
float Elements[100];
public:
FloatRangeProxy operator [] (const Range& r)
{
return FloatRangeProxy( Elements + r.begin, Elements + r.end );
}
};[/code] Edited by Hodgman

Share this post


Link to post
Share on other sites
Matt-D    1574
As an inspiration, you can also look at open-source NT2 @ [url="http://github.com/MetaScale/nt2/"]http://github.com/MetaScale/nt2/[/url] which has a placeholder operator, nt2::_.
Example usage:
[source lang="cpp"]using nt2::_;

nt2::table<T> a0, a1, b0, b1, a, b, c;

a1 = nt2::sum(a0(_));
b1(_,_,1) = 0.5*b0(_,_,1);
c = nt2::horzcat(a(_), b(_));

c = b(3, _);
b(3, _) = b(2, _);
b(2, _) = c;
[/source]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this