Array

# C++ Array §

Some notes for myself for everything I learned that are helpful in competitive programming.

min_element and max_element

int myints[] = {3,7,2,5,6,4,9};
// using default comparison:
cout << *min_element(myints,myints+7) << '\n';
cout << *max_element(myints,myints+7) << '\n';

Initialize on the Heap Memory

int *arr = new int;

Working with Ranges

sort(a, a+n);
reverse(a, a+n);
random_shuffle(a, a+n);

### Polymorphic Array §

It you try to do Polymorphism with arrays, you might easily run into issues…

class Vec2 {
int x,y;
public:
Vec2(int x, int y): x{x}, y{y} {}
};

class Vec3: public Vec2 {
int z;
public:
Vec3(int x, int y, int z): Vec2{x,y}, z{z} {}
};

void f(Vec2* a) {
a = Vec2{7,8};
a = Vec2{9,10};
}

Vec3 myArray = {Vec3{1,2,3}, Vec3{4,5,6}};

f(myArray);

What does f expect:

a.  a ...
[x, y, x, y, ]


What it actually looks like:

a.  a ...
[7, 8, 9, 10, 5, 6]


Data ends up misaligned. All of Vec2{7,8} is written into myArray. Half of Vec2{9,10} is written into myArray, the other half is in myArray.

Lesson

Be very careful when using arrays of objects polymorphically. Solutions:

1. Use an array of pointers: Vec3* myArray
2. Use a vector of Vec3*

How does an array of pointers fix the issue?

..?