You can use an array to hold many objects of struct type instead of creating a single object everytime
But you can never substitute a struct for an array and vise versa, an array can hold multiple objects of struct type, however your question is not clear enough to deduce your idea clearly, I have just assumed that what you ment.
Lorence30:
If you want to pass a structure to a function, it's easier to pass the struct. Otherwise you'd have to pass each individual field, or the index.
Or what if you want to output the struct to a stream? It's easier to create operator <<() on the struct and then just do cout << myInstance;
What if you want member functions? Or private members? You can't do those with individual arrays.
There is potentially a performance penalty too: if you store the bits of the structure in separate arrays and there are lots of them, then each time you access one, you're hitting a different page in memory, possibly triggering a page fault.
Imagine following data:
Surname
Name
Middle name
DOB
Phone №
Address
You have 100 records of it.
Now you need to sort in by Surname and same Surnames should be sorted by Name.
With array of structs I can do this with two lines. Thing how you would do this with parallel arrays.
I can remove all persons livin on Oak st. with one line. Try to do this with parallel arrays
Structs support custom constructors, methods, polymorfism, encapsulation and much more. Arrays are not.
Or benefit. If the separate values are in different cache lines (but no page fault), then accesses might actually improve. Either way, this is hardware-specific deep magic.
I think you're missing that you can also have an array of structs.
Structs or classes are ideal for keeping related information.
Keeping data in individual arrays as in your second snippet loses the relationship between the information (name & price).
As dhayden pointed out, I can pass a specific weapon to a function.
1 2
display (weapons[2]);
Here I would take exception to your naming the struct "shop". An instance of your struct is not representing a shop, but rather a particular item of inventory. So I would call it an Item. A shop or store typically has a collection of Items to sell.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
struct Item
{
private:
string name;
int price;
int on_hand; // How many of this item are available
public:
// Construct an Item
Item (string nm, int pr, int oh);
// Actions to take on item
void Sell (int qty);
void restock (int qty);
// Print out an item
friend ostream & operator << (ostream & os, const Item & item);
};