0

I have a c array which contains valarrays as shown in the following code snipper,

#include <iostream>
#include <valarray>
#include <math.h>

using namespace std;

typedef uint uint32_t;
typedef std::valarray<uint32_t> uivector;

int main()
{
    uivector a[] = { uivector(uint32_t(1),8), uivector(uint32_t(2),4), uivector(uint32_t(3),5) };
}

Now how do I access, say, the third element of the second valarray (the value there is 2), without making any copies and in a single line statement? Is it possible to overload the [] operator to achieve the same? something like a[1][2]?

Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
Naveen
  • 458
  • 1
  • 10
  • 29

1 Answers1

1

The the third element of the second valarray is indeed a[1][2]. The subscripting operator is already overloaded by std::valarray. No copies are made, the value of the expression a[1][2] is the actual object contained in the valarray.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • No there is a problem with this. Try a index that goes out of bounds like a[1][20] and you will still see zero being printed out and it doesn't show index out of bounds error. – Naveen Feb 24 '17 at 19:15
  • Is it possible to overload the second [] operator to do out of bounds check? – Naveen Feb 24 '17 at 19:18
  • @Naveen: No. Just like with built-in array types, subscripting does not bounds check on `valarray` either. You cannot change that behaviour. – Kerrek SB Feb 24 '17 at 19:19