Jasha Jasha - 22 days ago 9
C++ Question

C++ range-based for loop over valarray rvalue is not working

I would like to iterate over a temporary valarray, but it isn't working. Here is my (non-working) code:

#include <iostream>
#include <valarray>
int main()
{
using namespace std;
valarray<int> numerators = {99, 26, 25};
valarray<int> denominators = {9, 2, 5};
for (int i : numerators / denominators) { cout << i << ","; }
// lots of errors
return 0;
}


Below is a minimal working example of what I would like to achieve, except that I don't want to define an object like
temp_array
.

#include <iostream>
#include <valarray>
int main()
{
using namespace std;
valarray<int> numerators = {99, 26, 25};
valarray<int> denominators = {9, 2, 5};
valarray<int> && temp_array = numerators / denominators;
for (int i : temp_array) { cout << i << ","; }
// prints 11,13,5,
return 0;
}


My compiler is g++ version 4.8.5 (Red Hat 4.8.5-4).
I am compiling with the -std=c++0x flag.

I've tried other syntax such as
for (auto&& i : temp_array)
and
for (int const & i : temp_array)
, but it doesn't work.

Answer

As pointed out in @Yam Marcovivc's answer the operation result isn't guaranteed to be a std::valarray<int> that can be passed directly to std::begin(). A temporary constructed object does the trick:

#include <iostream>
#include <valarray>
int main()
{
        using namespace std;
        valarray<int> numerators = {99, 26, 25};
        valarray<int> denominators = {9, 2, 5};
        for (int i : valarray<int>(numerators / denominators)) { 
            cout <<  i << ","; 
        }
        return 0;
}

See a Live Demo

Comments