Data Types, Arrays and Strings

Simple and Structured Data Types:

A simple data type can store only one value at a time. A structured data type is one in which each data item is a collection of other data items. In a structured data type, the entire collection uses a single identifier (name). The purpose of structured data types is to group related data of various types for convenient access using the same identifier. Similarly, data can then be retrieved as an aggregate, or each component (element) in the collection can be accessed individually. Furthermore, a structured data type is a user-defined data type (UDT) with elements that are are divisible, and can be used discretely or as a single unit, as appropriate.

C++ simple data types:

  1. integral (char, short, int, long, and bool)
  2. enum
  3. floating (float, double, long double)
C++ structured data types:
  1. array
  2. struct
  3. union
  4. class
***Even though individual characters in a string can be accessed, the string data type is not considered a structured data type.

Arrays

Description:

Array Basics: Declaring Arrays: Initializing Arrays: Accessing Array Elements: Processing One-Dimensional Arrays (basic array operations using iteration):
  1. Initialize
  2. Input
  3. Output
  4. Sum and Average
  5. Find largest element value
  6. Find smallest element value
  7. 
      //initialize named constant
      const int arraySize=5;
    
      //declare array list with arraySize elements of type double 
      double list[arraySize];
    
      //initialize 7 variables
      int i=0;
      double smallest=0.0;
      double largest=0.0;
      double sum=0.0;
      double average=0.0;
      int maxi=0;
      int mini=0;
    
      //1. initialize each element in array list to 0.0, beginning w/first element
      for (i=0; i < arraySize; i++)
        list[i]=0.0;
    
      //2. input value for each element in array list, beginning w/first element
      for (i=0; i < arraySize; i++)
        cin >> list[i];
    
      //3. output value for each element in array list, beginning w/first element
      for (i=0; i < arraySize; i++)
        cout << list[i] << " ";
    
      //4. sum and average elements in array list, and display
      for (i=0; i < arraySize; i++)
        sum = sum + list[i];
        average = sum / arraySize;
    
        cout << "Sum = " << sum;
        cout << "\nAverage = " << average;
    
      //5. find largest element value in array list, and display
      for (i=0; i < arraySize; i++)
          if (list[maxi] < list[i])
    	 maxi = i;
          largest = list[maxi];
          
        cout << "\nLargest = " << largest;
    
      //6. find smallest element value in array list, and display
      for (i=0; i < arraySize; i++)
          if (list[mini] > list[i])
    	    mini = i;
    	smallest = list[mini];
      
        cout << "\nSmallest = " << smallest;
     
Array Index Out of Bounds

  //declare array with 10 elements of type double
  double num[10];

  //declare index variable
  int i;
Array Initialization Array Partial Initialization Array Processing Restrictions
  1. C++ does not allow aggregate operations on arrays (e.g., assignment, reading and printing contents of array--must be done element-wise)
  2. Aggregate operation: any operation that manipulates entire collection (e.g., array) as single unit
  3. 
      int myArray[5] = {2, 4, 6, 8, 10};
      int yourArray[5];
    
      yourArray = myArray; //illegal assignment 
    
  4. Must perform member-wise copy:
  5. 
      int myArray[5] = {2, 4, 6, 8, 10};
      int yourArray[5];
    
      //legal, member-wise copy
      for (int i=0; i < 5; i++)
        yourArray[i] = myArray[i];
    
  6. Same with IO: must perform member-wise instructions:
  7. 
      int myArray[5];
    
      cout << myArray; //illegal
      cin >> myArray; //illegal
    
      //legal, member-wise input
      for (int i=0; i < 5; i++)
        cin >> myArray[i];
    
      //legal, member-wise output
      for (int i=0; i < 5; i++)
        cout << myArray[i];
    
Arrays as Parameters Array's Base Address:

Intro to Vectors


Arrays vs. Vectors

Problems with Arrays vs. Vectors (and other containers: list, map, etc.):

An array is a homogeneous data structure (elements have same data type) that stores a sequence of consecutively numbered objects--allocated in contiguous memory. Each object of the array can be accessed by using its number (i.e., index). When you declare an array, you set its size. (It's possible to create "dynamic" arrays, but still array sizes, once set, cannot be altered). The array cannot hold any more elements than its initial size. For example:

int myArray[] = new int[5];
This snippet of code will create an array (on the "heap" or "free store" memory, using the new keyword) holding up to five integers. If more elements are desired (say, a 6th or 7th integer), a larger array will need to be declared, and all of the elements from the old array copied into the new one--and adding the 6th or 7th integer to the new array.

For these and other reasons, arrays can be difficult to use reliably...

What's wrong with arrays? Vector benefits:

  void f(int a[], int s)
  {
      // do something with a; the size of a is s
      for (int i = 0; i < s; ++i) a[i] = i;
  }

  int arr1[20];
  int arr2[10];

  void g()
  {
      f(arr1,20);
      f(arr2,20);
  }
The second call will write all over memory that doesn't belong to arr2. Generally, a programmer will get the size right, but it's extra work, and, sometimes, every so often someone makes the mistake. A simpler and cleaner version using the standard library vector:
  void f(vector& v)
  {
	// do something with v
	for (int i = 0; i < v.size(); ++i) v[i] = i;
  }

  vector v1(20);
  vector v2(10);

  void g()
  {
	f(v1);
	f(v2);
  }
Since an array doesn't know its size, there can be no array assignment:
  void f(int a[], int b[], int size)
  {
	a = b;	// not array assignment
	memcpy(a,b,size);	// a = b
	// ...
  }
Again, vector:
  void g(vector& a, vector& b, int size)
  {
	a = b;	
	// ...
  }
Another advantage of vector here is that memcpy() is not going to do the right thing for elements with copy constructors, such as strings.
  void f(string a[], string b[], int size)
  {
	a = b;	// not array assignment
	memcpy(a,b,size);	// disaster
	// ...
  }
Using vector...
  void g(vector& a, vector& b, int size)
  {
	a = b;	
	// ...
  }
An array is of a fixed size determined at compile time (unless placed on the "free store" or "heap" and accessed through pointers):
  const int S = 10;

  void f(int s)
  {
	int a1[s];	// error
	int a2[S];	// ok

	// to extend a2, must change to an array
	// allocated on free store using malloc() and use realloc() (C-style)
	// ...or, use new and delete (C++-style)
  }
In contrast using vectors:
  const int S = 10;

  void g(int s)
  {
	vector v1(s);	// ok
	vector v2(S);	// ok
	v2.resize(v2.size() * 2);
	// ...
  }
Benefits of Arrays over Vectors: Consider the following snippet of code...
static const char* suits[4] = { "Hearts", "Diamonds", "Clubs", "Spades" };
Will this list change during the program life-cycle? No. Will members need to be manipulated, searched, or various other operations performed? No. We just need a reference list. Do we need a vector? No.

Much of the time, just need to allocate space for storage. That is, hold some data somewhere. The art of programming is choosing the right tool for the job.