i'm learning arrays , how work. i'm given following function used find maximum elements in 3 different arrays, a, b , c:
void findmax(int a[], int b[], int c[]) { int maxa = a[0], maxb = b[0], maxc = c[0]; (int = 1; < max_len; i++) { if(maxa < a[i]) maxa = a[i]; if(maxb < b[i]) maxb = b[i]; if(maxc < c[i]) maxc = c[i]; } } my goal figure out how return 3 values (maxa, maxb, maxc) without adding arguments. i'm allowed change return type , can write code outside function.
my first thought change void int , create new array has 3 max values. however, think need pointers return arrays , haven't learned yet.
there few ways approach this.
the traditional approach (arrays)
the easiest way make function return int[]. gives of values , in concise format. however, int[] type cannot guarantee size 3 or contains claim contains, not type-friendly approach.
the oo approach (structs)
most java enthusiasts tell make struct or class encapsulates idea, such this.
struct maxvals { int maxa; int maxb; int maxc; // possibly constructor here }; this still memory-efficient solution , cleaner array approach. has benefit of being more type-safe; can't make maxvals 4 or 2 ints now; it's guaranteed @ compile-time have 3. however, bulky. requires define new type, outside of function, ever used in 1 case.
the modern approach (tuples)
this new feature of c++, adapted python , haskell, it's available in c++11, has limited support across compilers. tuples new data structure in tuple header can guarantee heterogeneous, fixed-size data structures of types specify @ compile-time. set return type std::tuple<int, int, int> , initialize structure std::make_tuple(maxa, maxb, maxc).
this approach has same memory advantages , guarantees struct approach without overhead , boilerplate of declaring one-use type. ideal approach problem this, if compiler supports it.
Comments
Post a Comment