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[5];

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[0] = Vec2{7,8};
	a[1] = Vec2{9,10};
}
 
Vec3 myArray[2] = {Vec3{1,2,3}, Vec3{4,5,6}};
 
f(myArray);

What does f expect:

a[0].  a[1] ...
[x, y, x, y, ]

What it actually looks like:

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

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

Lesson

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

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

How does an array of pointers fix the issue?

..?