Arrays and Vectors ❤️


Section Overview:

  • Arrays
    1. What they are 
    2. Why we use arrays
    3. Declaration and Initialization
    4. Accessing array elements
  • Multi-Dimensional Arrays
  • Vectors 
    1. what they are 
    2. Advantages vs arrays
    3. Declaration and Initialization
  • Interesting Exercise

What are Arrays?

An array contains a group of elements with the same data type, Basically, we use arrays to organize the data so that the related values can be easily sorted and searched.

Examples:
  • A search engine may use an array to store Web pages found in a search performed by the user. The program will display only one element of the array at a time. This may be done for a specified number of values or until all the values stored in the array have been output. Storing the result in an array is a much more efficient way to manage memory.

Why we use Arrays:

  • We know that array is a collection of data, but it is often more useful to think of an array is a collection of variables of the same type.
  • Instead of declaring individual variables, such as a number(), number1, ..., and numbers10000, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[10000] to represent individual variables. A specific element in an array is accessed by an index.
  • The lowest address in the array corresponds to the first element and the highest address corresponds to the last element.

How does it work:

  • The name of the array represents the location of the first element in the array(index 0).
  • The [index] represents the offset from the beginning of the array.
  • C++ performs some calculation to find the correct element of an array.
  • Remember, No Bound Checking (Explained detailedly in fig 0.2 ).
Declaration and Utilization:
Declaration of an array

Element_type Array_Name [Constant number of elements] {init list};

The syntax of an array declaration is very simple first we will write the type of an array followed by name of an array, then we provide the square brackets which is the array indexing operator, and in this square bracket, we will declare the size of an array which is fixed. 
  • In the first example given below, we are declaring the size of the array(test_scores) of 5 integers and assigning the values respectively {100, 95, 98, 87, 88}.
  • In the second example, we are performing the same as first but instead of declaring 10 values we declared only 2 values respectively and the remaining values are assigned as 0.
  • In the last example(vowels) given below, we have not assigned any size for an array, instead, I am letting the compiler to determine the size. In this case, another array will be of 5 characters or any respective and each will be initialized from 'a' to 'u'.  

fig 0.1
Accessing and Modifying elements:
Accessing array elements

Array_name[Element_Index]


fig 0.2


fig 0.3
  • Syntax of accessing array elements is really funny, but the important note is indexes of an array starts from 0 to N-1, where N is the size of an array. In fig 0.2 we printed test_score elements starting from index 0 to 4 (N-1 = 4, where N = 5(100, 90, 80, 70, 60)).
  • We can modify array elements if the type of array is int, double, etc... rather than a constant because constant keyword allows the user to initialize a variable that is constant for the complete program.
  • In fig 0.3 To modify array elements first we need to access that array element and initializing it to the respective value in respective position. For example ->  hi_temps[0] = 90.1 to hi_temps[0] = 100.7.
  • In the same way, we can take inputs directly as shown in fig 0.4  from the console and initialize them into an array by using inbuilt I/O streams of C++.

Out of Bounds:

  • In Fig 0.2  (Commented line) shows the array index out of bounds error, it is a special case of the buffer overflow error. It occurs when the index used to address array items exceeds the allowed value. It's the area outside the array bounds which is being addressed, that's why this situation is considered a case of undefined behavior. The absence of array overrun control in C and C++ is the factor that makes this error possible.
fig 0.4

Declaring Multi-Dimensional Arrays:

Declaration of Multi-Dimensional Array

Element_Type Array_Name [dim1_size][dim1_size]


fig 0.5


fig 0.6

The syntax of a Two-Dimensional array declaration is very simple first we will write the type of an array followed by name of an array, then we provide two square brackets which is the array, indexing operator, and in this square bracket, First bracket is to declare the size of rows and Second one is to declare the size of columns we will declare the size of an array which is fixed.
In the first example int movie_rating[3][4] we defined 3 rows and 4 columns, we can also declare in another format as described in fig 0.5 declaring the constants and assigning those constants as values of rows and columns.
We can also initialize or modify the existing or new 2D-Array in the given format in fig 0.7.
First, we will declare the size of rows and columns with respective names and type of an array, and push the respective elements in the given format in fig 0.7.




fig 0.7

Accessing and modifying 2D-Array Elements :

Accessing and modifying 2D-Array elements is almost the same as accessing and modifying One Dimensional array elements with some modifications. Here we need to give respective row and column positions of element to access it and modify with a new element.
In fig 0.8 1 denotes the row and 2 denotes the column and it displays the respective element from the array.

 fig 0.8

What are Vectors?

  • A container in the C++ Standard Template Library.
  • An array that can grow and shrink in size at execution time.
  • It provides similar semantics and syntax as arrays.
  • Very efficient.
  • Can provide bounds checking.
  • It can use lots of cool functions like sort, reverse, find and more.
Example:
  • Suppose we want to store the test score for my school.
  • I have no way of knowing how many students will register next year.
Options:
  • Pick a size that you are not likely to exceed and use static arrays.
  • Use dynamic array like a Vector.
Declaring and initializing vectors :

There are several ways to declare a vector, vectors are objects. We can create any type of vector we want. We must include the type of vector in angle brackets. Both of these vectors contain no elements.
 

fig 0.10 

In the first example, we declare vowels to declare a vector containing 5 characters. In the second example we declared that we need 10 integers. Unlike arrays, vectors arrange 0 to uninitialized elements.

fig 0.11 

In fig 0.12 first example contains 5 characters, the Second example contains 4 integers, But the third example is different from the above two. Here we are using a constructor in a vector that contains two key values they are some of the vector and the values of the vector. In the third example, we denoted in such a way that the size of the vector is 35 and all 35 values are assigned to 85.0.


fig 0.12

Characteristics of Vectors :


  • Dynamic Size 
  • Elements are all of the same sizes
  • Stored contiguously in memory
  • Individual elements can be accessed by their position or index.
  • The first element is at 0 
  • The last element is at -1
  • [] - no checking to see if you are out of bounds.
  • It provides many useful functions that do bounds check.
  • Elements initialized to zero.
  • Elements initialized to 0.
  • Very efficient.
  • Iteration is often used to process.



fig 0.13

Here in the above figure, we can access an element using the syntax in the array while accessing the element by describing its position. We can also use .at(Index_of_element) || .at(row_index).at(column_index). In the same way, we can push element into a vector using  .push(Index_of_element) || .push(row_index).push(column_index)

Interesting Exercise:



Comments

Popular posts from this blog

Basic things You need to Know in C++😁