Date Tags Arrays / C++

Note: I have always heard that the best way to learn something, is to teach it to others. So this article is my own summary of what I am learning in my CS 161 class, written from the perspective of trying to teach it to someone. I do have some prior experience with C/C++ but I am definitely not trying to pass myself off as some kind of C/C++++ super expert! :) If you see something blatantly wrong, then please contact me so I can get it fixed!

# What is an Array?

According to Wikipedia, "An array is a systematic arrangement of similar objects, usually in rows and columns."

In programming languages like C/C++ an array is a datatype that allows you to work with multiple values of the same datatype.

## Decalaring an array of integers

```int myArray;
```

This delcarees an array of intergers named `myArray` that can hold up to 10 integer elements.

The `` is known as the array size declarator and it defines the maximum number of elements that the array can hold. In this case it is 10. The array size declarator can either be a literal or a named constant like the following:

```const int SIZE = 10;
int myArray[SIZE];
```

## Array memory requirements

The memory requirements of an array depend on the size of that datatype for your system and the max number of elements of the array. Here is a simple example for finding out how much memory your array is reserving.

```#include <iostream>
using namespace std;

int main()
{
cout << "The size of an integer on your system is: "
<< sizeof(int) << " bytes." << endl;

int myArray;
cout << "myArray has " << sizeof(myArray) << " bytes reserverd for it." << endl;

return 0;
}
```

## Accessing individual array elements

You can access individual array elements by using array notation

```int myArray = {100, 200, 300, 400, 500};
cout << myArray;
cout << myArray;
cout << myArray;
```

## Pronouncing expressions with array notation

```hours = 20;
```

The above expression would be pronounced as "hours sub zero is assigned twenty".

## Zero Indexing

Arrays in C, C++, Python and many other languages are 0 indexed meaning that the index of the first element is 0, the second is 1, etc. {: .img-responsive .center-block }

## No bounds checking in C++

Keep in mind that in C++ there is no bounds checking. This means that there is nothing to stop you from writing a program that tries to put more elements into an array than memory has been set aside for that array.

The following program will compile on many systems but will cause a segmentation fault (Meaning that your program is trying to access a portion of memory that does not belong to it) when executed.

```#include <iostream>
using namespace std;

int main()
{
int myArray = {100, 200, 300, 400, 500};
myArray = 600;

cout << myArray;
return 0;
}
```

## Can be initialized when defined.

You can store array elements when an array is declared by doing something similar to the following:

```int days[NUM_MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
```

## Partial initialization.

You don't have to initialize all of the elements of an array when you define it.

```int myArray = {100, 200, 300};
```

Note that any of the uninitialized values will be initialized with a value of 0. {: .img-responsive .center-block }

An array of partially initialized strings would have the empty values populated with empty strings.

```string strArray = {"Hello", "C++", "World!"};
``` {: .img-responsive .center-block }

## Implicit Array Sizing

You can let C++ do the counting work for you and just provide a list of values by doing the following.

```int myArray[] = {100, 200, 300};
```

## Parallel Arrays

You can build primitive relationships between values in two arrays by using the same subscript to access both arrays.

## Typedef with Arrays

You can use the typedef statement to define alias for a dataype.

```typedef double score;
score finalExam;
// declares an array with 100 double elements
```

## Arrays are passed by reference (sort of)

Just like in C, it is not possible to pass arrays by value but only by reference. Well, sort of.

Technically, everything in C is passed by value and you only use pointer addresses to simulate passing by reference. C++ appears to behave similarly, at least for arrays.

```#include <cstdio>
#include <iostream>

using namespace std;

void printIntArray(int array[], int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
cout << array[i] << endl;
}
}

int main()
{
int myIntArr[] = {100, 200, 300};
int myArrSize = 3;

printIntArray(myIntArr, myArrSize);

return 0;
}
```

Click here to access and run the above code on codepad.org

In the above code, in the header for `printIntArray()`, the array is actually passed by reference (simulatedly) because `array[]` is a pointer (technically, it decays to a pointer) to the first element in that array.

## `const` with Array Parameters

Just as in C, you can use the `const` keyword to specify that the function should not be allowed to change the values the array.

```#include <iostream>
using namespace std;

void printIntArray(const int array[], int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
cout << array[i] << endl;
}
}

int main()
{
int myIntArr[] = {100, 200, 300};
int myArrSize = 3;

printIntArray(myIntArr, myArrSize);

return 0;
}
```

Click here to access and run the above code on codepad.org

## 2 Dimensional Arrays

C++ can handle arrays of many dimensions and the code below shows how to pass a 2d array into a function.

```#include <iostream>
using namespace std;

void printIntArray(const int table[], int numCols, int numRows)
{
for (int k = 0; k < numRows; k++)
{
for (int i = 0; i < numCols; i++)
{
cout << table[k][i] << " ";
}
cout << endl;
}
}

int main()
{
int myIntTable[] = {{100, 200, 300, 10},
{400, 500, 600, 20},
{700, 800, 900, 30}};
int numCols = 4;
int numRows = 3;

printIntArray(myIntTable, numCols, numRows);

return 0;
}
```

Click here to access and run the above code on codepad.org

Notice that in the code above, though we can let C++ figure out the size of the rows dimension, we must specify for it the size of the inner-most or columns dimension.

Keep in mind, that just like in C, the size of arrays must be known at compile time and so you must turn to other data scructures if you want a dynamically sizeable array-like data structure.

If only there were some built in type of data structure in C++ that could be dynamically sized and randomly accessed like an Array...

## Vectors

The Standard Template Library or STL contains datatype that are commonly called containers because they contain and organize data. There are two types of cotainers, sequence containers and associative containers. Associative containers are your standard associative arrays that map keys to values, while sequnce containers are more like lists or one dimensional arrays.

• Holds a sequnce of values/elements
• Stored in contiguous memory locations (side by side).
• You can use the array subscript operator `[]` to randomly access the vector.

• you do not have to declare the number of elements that the vector will have
• the vector will automatically increase in size if you try to add to a vector that is already full.
• vectors can report the number of elements they contain.

```#include <vector>
```

Creating a Vector Object:

```vector<int> numbers;
```

Creating a Vector Object and optionally declaring a starting size:

```vector<int> numbers(10);
```

You may also specify an initialization value for the vector. This value will be copied to all elements when it is created:

```vector<int> numbers(10, 2);
```

Creating a vector that is a copy of another vector:

```vector<int> set2(set1);
```

Storing Values into a Vector with array notation:

```vector<int> numbers(10, 2);
numbers = 1;
numbers = 2;
// etc...
```

You cannot use array notation though to store values into a vector that do not exist yet. So, to add a number to the position  in the vector, we must use the `push_back()` member function:

```vector<int> numbers(10, 2);
numbers = 1;
numbers = 2;
// etc.
numbers.push_back(11);
```

Some other helpful vector member functions:

```numbers.size()
// returns the number of elements in numbers.

numbers.pop_back()
// removes the last element of a vector.

numbers.clear()
// clears the contents of a vector.

numbers.empty()
// returns true if the vector is empty, etc.
```

## Arrays of Objects and Structs

In C, you can have an array of any valid datatype and C++ seems to be no different. You can easily define arrays of objects as long as they are all of the same class.

For instance, say you had a class named `Car`, you could declare an array of 10 car objects with the following code:

```Car myCars;
```

You can also define arrays of structs as long as they are of the same struct type.

```struct Car
{
string color;
string engine;
string price;
double emissionsRate;
};

Car myCars;
```

That about sums up the major topics my book covered for arrays and vectors.

Next I will be going through the basics of Pointers. Luckily, because of my experience with C through CS50, I have a decent amount of experience with pointers!