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:C++ structured data types:
- integral (char, short, int, long, and bool)
- enum
- floating (float, double, long double)
***Even though individual characters in a string can be accessed, the string data type is not considered a structured data type.
- array
- struct
- union
- class
Description:
//intExp evaluates to positive integer--indicates number of elements dataType arrayName[intExp]; //declares array num containing 5 elements of type int: //num[0], num[1], num[2], num[3], and num[4] int num[5];
//Index value (intExp) specifies position of element in array arrayName[intExp] //fifth element in array num num[4];
//declare array item with five elements of type int int item[5]; //assign value 35 to 5th element in item array item[4]=35; //assign value 10 to 4th element in item array item[3]=10; //assign value 45 to 3rd element in item array item[2]=item[3] + item[4];Processing One-Dimensional Arrays (basic array operations using iteration):
//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;
//declare array with 10 elements of type double double num[10]; //declare index variable int i;
double sales[] = {12.25, 32.50, 16.90, 23, 45.68}; //same result as... double sales[5] = {12.25, 32.50, 16.90, 23, 45.68};
// Fig. 7.3: fig07_03.cpp // Initializing an array's elements to zeros and printing the array. #include <iostream> #include <iomanip> using namespace std; int main() { int n[ 10 ]; // n is an array of 10 integers // initialize elements of array n to 0 for ( int i = 0; i < 10; ++i ) n[ i ] = 0; // set element at location i to 0 cout << "Element" << setw( 13 ) << "Value" << endl; // output each array element's value for ( int j = 0; j < 10; ++j ) cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl; } // end main
// Fig. 7.4: fig07_04.cpp // Initializing an array in a declaration. #include <iostream> #include <iomanip> using namespace std; int main() { // use initializer list to initialize array n int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; cout << "Element" << setw( 13 ) << "Value" << endl; // output each array element's value for ( int i = 0; i < 10; ++i ) cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl; } // end main
// Fig. 7.5: fig07_05.cpp // Set array s to the even integers from 2 to 20. #includeArray Partial Initialization#include using namespace std; int main() { // constant variable can be used to specify array size const int arraySize = 10; // must initialize in declaration int s[ arraySize ]; // array s has 10 elements for ( int i = 0; i < arraySize; ++i ) // set the values s[ i ] = 2 + 2 * i; cout << "Element" << setw( 13 ) << "Value" << endl; // output contents of array s in tabular format for ( int j = 0; j < arraySize; ++j ) cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl; } // end main
int num[5] = {0};
int n[10] = {}; //initialize all elements of array n to 0
int num[5] = {8, 5, 12};
int num[] = {5, 6, 3};
int num[100]= {4, 7};Array Processing Restrictions
int myArray[5] = {2, 4, 6, 8, 10}; int yourArray[5]; yourArray = myArray; //illegal assignment
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];
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];
//Function to print array: //array and number of elements passed to parameters //listSize specifies number of elements to be printed void printArray(const int list[], int listSize) { int counter; for (counter = 0; counter < listSize; counter++) cout << list[counter] << " "; }
//Call to function printArray(), list is one-dimensional array //arraySize is scalar variable of type integer printArray(list,arraySize);Array's Base Address:
vector< type > name( size );
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:
- Unknown size: arrays don't know their own size
- Fixed size: can't modify once set
- Lack of subscript (range) checking: can go out-of-bounds, (cause for buffer overflow)
- Array name converts to a pointer to its first element (potentially causing problems--any of the above)
- easier to write
- easier to read
- less error prone
- in many applications, just as fast, also...
- inherent support to: add new elements beyond current size, resize, sort, search, erase elements, etc.
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(vectorSince an array doesn't know its size, there can be no array assignment:& 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); }
void f(int a[], int b[], int size) { a = b; // not array assignment memcpy(a,b,size); // a = b // ... }Again, vector:
void g(vectorAnother advantage of vector here is that memcpy() is not going to do the right thing for elements with copy constructors, such as strings.& a, vector & b, int size) { a = b; // ... }
void f(string a[], string b[], int size) { a = b; // not array assignment memcpy(a,b,size); // disaster // ... }Using vector...
void g(vectorAn array is of a fixed size determined at compile time (unless placed on the "free store" or "heap" and accessed through pointers):& a, vector & b, int size) { a = b; // ... }
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) { vectorv1(s); // ok vector v2(S); // ok v2.resize(v2.size() * 2); // ... }
char myChar[] = "Test"; //array of 4 characters
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.