Cpp datastructures & types

From wikinotes


C++ allows you to create your own datastructures, which is really interesting. It works something like a relative to a class and dict type in python.


Datastructures

Structs

// Define a new type 'product' that is
// composed of (int, double)
struct product {
	int    weight;
	double price;
};

product apple;
product banana;


// Alternatively, you can declare variables
// immediately following the type
struct prodct {
	int    weight;
	double price;

} apple, banana;



apple.weight = 50;
apple.price  = 500.0;

Using Pointers

struct product {
	int    weight;
	double price;
};


product honda_civic;


product * my_car;
my_car          = &honda_civic;
my_car->weight  = 500;
(*my_car).price = 8000.51;



Types

Type Aliases

typedef int num;	// alias 'int' type as 'num'
using   int num;	// alias 'int' type as 'num'

num height = 6;


Unions

Unions are defined like a struct, except that unlike a struct, each attribute refers to the same value. Each datatype provides a different view to the same memory location.

struct product {
	char name[50];
	union {
		float dollars;
		int   yen;
	} price;
}

product car;

apple.name          = "honda_civic";
apple.price.dollars = 500.80;

cout << apple.price.yen;		## 501;


Enum

Enums are a fixed-size list of options (think a dropdown menu). They types are equivalent to ints.

enum months { jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };

// Both of these statements are identical
if ( months == jan )   cout << "hi" << endl;
if ( months == 0   )   cout << "hi" << endl;


Class Enum/Struct Enum)

Class Enums are enums that can store a type. If I understand this correctly, you could define your own types, and check if the enum is one of those.


enum class EyeColour : char {blue, green, brown};


char eyecolour[10] = "brown";
if (eyecolour == EyeColour::brown){
	cout << "Eye colour is brown" << endl;
}