Re: A malloc error in C++ - incorrect checksum for freed object
In article <5k0qkhF1lqjbU1@mid.dfncis.de>, bloodymir.crap@gmx.net
says...
[ ... ]
I don't like the idea of having a vector full of identical values just
for using it with inner_product. I _like_ the idea of using std
algorithms, though.
There is another way: make something that acts like a vector full of
identical values:
// warning: untested code
template <typename T>
class single_value {
T v_;
size_t size_;
public:
single_value(T v, size_t size) : v_(v), size_(size) {}
double operator[](size_t index) {
return v_;
}
friend iterator;
class iterator {
size_t pos_;
single_value v_;
public:
iterator(single_value const &v, size_t pos = 0)
: v_(v), pos_(pos)
{}
iterator &operator++() {
++pos;
return *this;
}
double operator*() { return v_.v_; }
bool operator==(iterator const &other) {
return pos_ == other.pos_;
}
};
iterator begin() { return iterator(this); }
iterator end() { return iterator(this, size_); }
}
Another possibility would be to use valarrays. They were really intended
for this kind of computational work, and can often handle it quite
cleanly:
// Warning: only minimally tested
template <class T>
T const variance(T *values, size_t size) {
std::valarray<T> const v(values, size);
T average = v.sum() / v.size();
std::valarray<T> diffs = v-average;
diffs *= diffs;
return diffs.sum()/diffs.size();
}
As this is written at the moment, it accepts a pointer and size, but it
would be fairly easy to allow it to accept input as a pair of iterators
or such. Given the OP's problem, using valarrays throughout might be a
possibility as well, and I didn't want to spend a lot of code on
something that might easily not matter.
Whether this is better or worse is open to some question -- on one hand,
it does temporarily store all the (squared) deviations from the mean, so
it uses extra memory that isn't strictly necessary. OTOH, I think it's
much easier to read and understand than either the original code or your
code. That's likely good in educational code, but not so good for a
library that will be used heavily but only rarely read. OTOH, for big
vector-based machines (e.g. Crays) most valarray operations are easy to
run on the vector processer, in which case they should be quite fast.
--
Later,
Jerry.
The universe is a figment of its own imagination.