Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

When to use a struct in a list?


Asked by Annabella Taylor on Dec 12, 2021 FAQ



A struct is a value type, and is passed by value. When you say myList [i].x = newX you're assigning to the x property of a copy of the i th element of myList, which would be thrown away after the statement is executed. Luckily the compiler will stop you from making this mistake.
Additionally,
Use a struct when you need to store elements of different data types under one data type. C++ structs are a value type rather than being a reference type. Use a struct if you don't intend to modify your data after creation.
Just so, struct (C++) The struct keyword defines a structure type and/or a variable of a structure type.
Moreover,
The struct members are added within curly braces. These members probably belong to different data types. In the above example, Person is a structure with three members. The members include name, citizenship, and age. One member is of char data type, while the remaining 2 are integers when a structure is created, memory is not allocated.
Next,
When you use [] operator on a list of class, the [] function is actually returning a reference to the original object and hence your modification on this reference object will cause the original element to change. Phew! One discovery that was. Next time you are creating a list of structs, remember this little piece of information. Beware!