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

Started by
1 comment, last by Matt-D 11 years, 9 months ago
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:

Array[range] = scalar;


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



class FloatArray
{
public:
float Elements[100];

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

//and operator
???? operator = (???)
{ }
};


To obtain this?

Regards,
Misery
Advertisement
Something along the lines of this code (untested), which returns a proxy object to perform the assignment should work: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 );
}
};
As an inspiration, you can also look at open-source NT2 @ http://github.com/MetaScale/nt2/ 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]

This topic is closed to new replies.

Advertisement