Fun with valarray.

S

Steven T. Hatton

Examine the following code before you compile and run it. What do you
expect to happen? Is what you expected consistent with the result of
running it?

#include <valarray>
#include <iostream>

using std::valarray;
using std::slice;
using std::cout;
using std::eek:stream;

valarray<size_t> makeValarray(const size_t& size) {
valarray<size_t> va(size);
for(size_t i = 0; i < va.size(); i++) { va = i + 1; }
return va;
}

template<typename T>
ostream& printValarray(const valarray<T>& va, ostream& out=cout) {
for(size_t i = 0; i < va.size(); i++) {
if(i){ out << ","; }
out << va;
}
return out << "\n";
}


valarray<size_t> nibble(const valarray<size_t>& va) {
return va[slice(1, va.size() - 1, 1)];
}

void spit() {
valarray<size_t> va = makeValarray(16);
while(va.size() > 1) {
printValarray(va);
va = nibble(va);
}
}

int main()
{
spit();
return 0;
}

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell
 
M

Markus Moll

Hi

Examine the following code before you compile and run it. What do you
expect to happen? Is what you expected consistent with the result of
running it?

Hm... I hadn't expected it. But then, I have virtually no experience with
valarrays. A short search told me that your code results in undefined
behaviour, so you shouldn't expect too much either :)
va = nibble(va);

Assignment to a valarray of different size is undefined.

Keep in mind that design decisions for valarray were made with respect to
efficiency. Furthermore, references to elements of a valarray remain valid
until resize is called or the lifetime of the valarray ends. Therefore
valarrays are _never_ implicitly resized.

You will need a temporary variable here:

valarray<size_t> va_tmp( nibble(va) );
va.resize(va_tmp.size());
va = va_tmp;


Markus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top