array of structures
All - I have two 2d structures (simplified version is below) and I need some advice.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
struct example{
int example_number;
string example_txt;
}
example[] = {
{0,"xyz"},
{1,"aaa"},
{0,"xxx"},
};
const size_t nexample = sizeof example / sizeof example[0];
struct other{
string first;
string second;
}
other[] = {
{"ffffff", "jjjjjjjj"},
{"cccccc", "dddddd"},
{"bbbb", "aaaaa"},
};
const size_t nother = sizeof other / sizeof other[0];
srand(static_cast<unsigned>(time(0)));
int a = 0;
a = rand() % nexample;
cout << example[a].example.txt << "\n";
cout << other[rand() % nother].first << "\n";
|
but what I really want to do is use variable
a to return 1 or 0 from
example and feed it into the cout
cout << other[rand() % nother]. 1 or 0 from exmple << "\n";
rather than using
first or
second.
I can do it with an if but I assume there is a better way
thanks for your help
bob
You lost me. Please try and explain more clearly.
So, what you want is a better way of doing the following, correct?
1 2 3 4 5 6 7 8 9 10
|
int val = getValue(); //either 0 or 1
if(val == 0)
{
cout<<other[rand() % nother].first;
}
else
{
cout<<other[rand() % nother].second;
}
|
You could use an array.
1 2 3 4
|
struct other
{
string stringArr[2];
}
|
Also, rename the array here to something besides "example" (and the same for the array "other"):
1 2 3 4 5 6 7 8 9 10
|
struct example{
int example_number;
string example_txt;
}
example[] = {
{0,"xyz"},
{1,"aaa"},
{0,"xxx"},
};
|
because you can't instantiate a struct of type "example" after that statement.
Last edited on
Topic archived. No new replies allowed.