From: Nick Hounsome on
On 4 Mar, 20:09, A <aragorn1...(a)gmail.com> wrote:

> template <class T>
> vec<bool> operator==(const T &a) const {
> vec<bool> tmp(false,length);
> for(int i=0; i<length; i++) {
> if(v[i] == a) {
> tmp[i] = true;
> }
> }
> return tmp;
>
> }
>
> This works great, but I would like to return the reference instead of
> the whole vector and would like to know how to do it. I am unable to
> make use of the "this" pointer as I am returning a "local vector". I
> would appreciate any help with this. thank you!

A reference to what?
You have no member vector<bool> to reference.

The way to avoid the temporary is to return an object that captures
the original vector and the value that you are comparing and presents
a vector like interface.
This allows you to eliminate allocation and defer all computation
until it is needed:

template <class T>
struct DeferredResult
{
const vec<T>& vec;
const T& val;
DeferredResult(const vec<T>& v,const T& x) vec(v),val(x){}
bool operator[] (int i) const
{
return vec[i] == val;
}
size_t size() const { return vec.size(); }
// other vector like methods. iterators etc.
}


template <typename T>
DeferredResult<T> operator==(const vec<T>& v, const T& val)
{
return DeferredResult(v,val);
}

auto result = (v == 42); // C++0x auto helps here
for(int i = 0; i < result.size(); ++i)
{
bool match = result[i];
....
}

This is just an outline. You can parametrize the collection type and
predicate too if you want.

This technique is especially important with matixes because it is
possible to defer whole sequences of operations and thus remove the
need for lots of temporary matrices

e.g. matrixA = matrixB * matrixB + matrixD

Can be programmed to require no intermediates at all!


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: Jeffrey Schwab on
On 3/4/10 6:19 PM, Daniel Kr�gler wrote:
> On 4 Mrz., 21:09, A<aragorn1...(a)gmail.com> wrote:
>> I am writing a "vector" class. I know about the STL but I prefer to
>> use this as I use this to create a "matrix" class later. I read that
>> using the inbuilt STL to create a matrix is not the best way to do it.
>
> This is correct, but have you considered std::valarray?

.....or Boost.uBLAS, or any of the many other matrix libraries already
available in C++?

At some point, one is forced to the conclusion that people just enjoy
writing new libraries in C++.


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]