-1

I have a struct that has hardcoded data in it, however I can't figure out how to get c++ to display the data. What I am trying is:

#include <iostream>
using namespace std;

const int MAX = 8;

struct test {
   int x[MAX] = { 16, 21, 308, 45, 51, 63, 17, 38 };
   float y[MAX] = { 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5 };
   int z[MAX] = { 8, 7, 6, 5, 4, 3, 2, 1 };
} id[MAX] = { 1, 2, 3, 4, 5, 6, 7, 8 };

int main() {
   for (int counter = 0; counter < MAX; counter++) {
       cout << id[counter].x << ", " << id[counter].y << ", "<< id[counter].z << endl;
   }
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

2 Answers2

0

I suggest you change your data layout:

struct Triplet
{
  int x;
  float y;
  int z;
};

Next, make a container of the values:

std::vector<Triplet> test;

Or

  Triple test[MAXIMUM_CAPACITY];

This should make your initializations easier.
It may also speed up your program by keeping relevant data closer together in the data cache.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

I can't figure out how to get c++ to display the data.

You've been shooting over regarding usage of hardcoded arrays.
You don't need to double up your dimensions for struct. Any struct initialization will preserve the necessary memory for it's members.

You probably meant to write something like

#include <iostream>
using namespace std;

const int MAX = 8;

struct test
{
   int x; // A simple int
   float y; // A simple float
   int z; // A simple int
} const id[MAX] = // Preserve the dimension. Note the const, to prevent changing the
                  // hardcoded values.
    // Initialize the triples as needed
    { { 16, 1.5, 8 } ,
      { 308, 2.5, 7 } ,
      // Place more triples here ...
      { 38, 8.5, 1 }
    };

int main()
{
   for (int counter = 0; counter < MAX; counter++)
   {
       cout << id[counter].x << ", " << id[counter].y << ", "<< id[counter].z << endl;
   }

   return 0;
}

See the Live Demo


The idiomatic c++ way to write this would be

struct test {
   int x; // A simple int
   float y; // A simple float
   int z; // A simple int
};

std::array<test,MAX> id {{
    { 16, 1.5, 8 } ,
    { 308, 2.5, 7 } ,
    // Place more triples here ...
    { 38, 8.5, 1 }
}};

See Live Demo

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190