Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types
|
|
- Janis Pope
- 6 years ago
- Views:
Transcription
1 Arrays - Vectors Data Types Data Type: I. set of values II. set of operations over those values Example: Integer I. whole numbers, to II. +, -, *, /, %, ==,!=, <, >, <=, >=,... Which operation is invalid or inaccurate for float? Data Types (C/C++) Scalar (or Basic) Data Types (atomic values) o Arithmetic types Integers short, int, long char, bool Floating points float, double, long double Composite (or Aggregate) Types: Arrays: ordered sequence of values of the same type Structures: named components of various types Spring 2018 Husain Gholoom Lecturer in Computer Science Page 1
2 Review: Arrays An array contains multiple values of the same type. Values are stored consecutively in memory. An array definition in C++: int numbers[5]; Array indices (subscripts) are zero-based numbers[0]... numbers[4] The subscript can be ANY integer expression: numbers[2], numbers[i], numbers[(i+2)/2] What operations can be performed over (entire) arrays??? First-Class vs Second-Class objects First-Class Objects can be manipulated in the usual ways without any restrictions - copy (=, assignment) - comparison (==, <,...) - input/output (<<, >>) Second-Class Objects can be manipulated only in restricted ways, may have to define operations yourself - Usually primitive (built-in) data types ( bool, int, float... ) - Primitive arrays are not first-class objects (copying elements of an array). Spring 2018 Husain Gholoom Lecturer in Computer Science Page 2
3 First-Class vs Second-Class Objects: strings First-Class Object: string class (standard library) - = - size() member function - ==, <, Second-Class Object: C-String (char array) - strcpy - strlen - strcat - strcmp Example of Second-Class Object Special functions The usual operators #include <string> int main () { char str1[]="sample string"; char str2[40]; char str3[40]; strcpy (str2,str1); strcpy (str3,"copy successful"); cout << str1<< endl << str2 << endl << str3 ; strcat (str3," Done"); cout << endl << str3; Spring 2018 Husain Gholoom Lecturer in Computer Science Page 3
4 First-Class vs Second-Class objects: arrays First- Class Object: vector class (standard template library) - = - size() member function - ==, <,... The usual operators Second-Class Object: primitive array - = does not copy elements - length undefined - ==, <,... do not perform as expected usual operations are not defined Vector and String Included in standard (template) library Class definitions used for first class objects The definitions provide an interface that hides the implementation from the programmer. Programmer does not need to understand the implementation to use the types. Vector: like an array, can contain elements of any single given type. Spring 2018 Husain Gholoom Lecturer in Computer Science Page 4
5 Using vectors Include file To define a vector give it a name, element type, and optional size (default is 0): vector<int> a(3); // vector a with 3 int elements // a[0], a[1], and a[2] Can use [ ] to access the elements (0-based): a[3] = 12; Vector Operation : The push_back() function appends val to the end of the vector. The pop_back() function removes the last element of the vector. vector<int> the_vector; for (int i = 0; i < 10; i++) the_vector.push_back(i); cout << "push_back -- > "; for (int i = 0; i < 10; i++) cout << the_vector[i] << " "; cout << endl << endl; for (int i = 0; i < 5; i++) the_vector.pop_back(); cout << "pop_back -- > "; for (int i = 0; i < 5; i++) cout << the_vector[i] << " "; Sample run: push_back - - > pop_back - - > Spring 2018 Husain Gholoom Lecturer in Computer Science Page 5
6 The size() function returns the number of elements in the vector. resize(int N ) : Resizes the vector V so that it contains exactly N elements. Example vector<int> the_vector; the_vector.push_back(6); the_vector.push_back(9); the_vector.push_back(12); the_vector.push_back(15); the_vector.push_back(18); cout << endl << "vector size is " << the_vector.size() << endl; cout << "push_back -- > "; for (int i = 0; i < the_vector.size(); i++) cout << the_vector[i] << " "; cout << endl << endl; for (int i = 0; i < 2; i++) the_vector.pop_back(); cout << endl << "vector size is " << the_vector.size() << endl; cout << "pop_back -- > "; for (int i = 0; i < the_vector.size(); i++) cout << the_vector[i] << " "; cout << endl << endl; the_vector.resize(1); cout << "after resize -- > "; for (int i = 0; i < the_vector.size(); i++) cout << the_vector[i] << " "; Sample Run vector size is 5 push_back -- > vector size is 3 pop_back -- > after resize -- > 6 Spring 2018 Husain Gholoom Lecturer in Computer Science Page 6
7 The front() function returns a reference to the first element in the vector. The back() function returns a reference to the last element in the vector. Example vector<int> the_vector; the_vector.push_back(6); the_vector.push_back(9); the_vector.push_back(12); the_vector.push_back(15); the_vector.push_back(18); cout << "The first element is " << the_vector.front() << " and \nthe last element is " << the_vector.back() << endl; Sample Run The first element is 6 and the last element is 18 Spring 2018 Husain Gholoom Lecturer in Computer Science Page 7
8 The assign() function either gives the current vector the values from start to end, or gives it num copies of val. This function will destroy the previous contents of the vector. Example vector<int> v; v.assign(10, 42); for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; cout << "\n\nthe size of the vector is " << v.size() << endl; v.push_back(15); v.push_back(120); cout << "\n\nthe size of the vector is " << v.size() << endl; v.assign(5, 40); for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; cout << "\n\nthe size of the vector is " << v.size() << endl; cout << endl; Sample run : The size of the vector is 10 The size of the vector is The size of the vector is 5 Spring 2018 Husain Gholoom Lecturer in Computer Science Page 8
9 The next example shows how assign() can be used to copy one vector to another: vector<int> v1; for (int i = 0; i < 10; i++) v1.push_back(i); vector<int> v2; v2.assign(v1.begin(), v1.end()); for (int i = 0; i < v2.size(); i++) cout << v2[i] << " "; // Note : you can use as shown in the example v3 = v2. vector<int> v3; v3 = v2; cout <<"\n" ; for (int i = 0; i < v3.size(); i++) cout << v3[i] << " "; Sample run : Spring 2018 Husain Gholoom Lecturer in Computer Science Page 9
10 The at() function returns a reference to the element in the vector at index loc. The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the vector. For example, consider the following code: vector<int> v(5, 1); for (int i = 0; i < 10; i++) { cout << "Element " << i << " is " << v[i] << endl; Sample run : Element 0 is 1 Element 1 is 1 Element 2 is 1 Element 3 is 1 Element 4 is 1 Element 5 is 0 Element 6 is 0 Element 7 is 0 Element 8 is 0 Element 9 is 0 Spring 2018 Husain Gholoom Lecturer in Computer Science Page 10
11 This code overruns the end of the vector, producing potentially dangerous results. The following code would be much safer: vector<int> v(5, 1); for (int i = 0; i < 10; i++) { cout << "Element " << i << " is " << v.at(i) << endl; Sample run : Element 0 is 1 Element 1 is 1 Element 2 is 1 Element 3 is 1 Element 4 is 1 terminate called throwing an exception Spring 2018 Husain Gholoom Lecturer in Computer Science Page 11
12 The capacity() function returns the number of elements that the vector can hold before it will need to allocate more space. The reserve( int n ) function requests that the vector capacity be at least enough to contain n elements. For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size, the other method calls the reserve function to achieve a similar goal: vector<int> v1(10); cout << "The capacity of v1 is " << v1.capacity() << endl; cout << "The size of v1 is " << v1.size() << endl; vector<int> v2; cout << "The size of v2 is " << v2.size() << endl; v2.reserve(20); cout << "The capacity of v2 is " << v2.capacity() << endl; Sample run: The capacity of v1 is 10 The size of v1 is 10 The size of v2 is 0 The capacity of v2 is 20 Spring 2018 Husain Gholoom Lecturer in Computer Science Page 12
13 The function clear() deletes all of the elements in the vector. The empty() function returns true if the vector has no elements, false otherwise. For example vector<int> v; for (int i = 0; i < 5; i++) { v.push_back(i); for (int i = 0; i < 5; i++) { cout << v[i] << " "; cout << endl; v.clear(); if (v.empty()) cout << "vector is empty"; else cout << "vector is not empty"; Sample run: vector is empty Spring 2018 Husain Gholoom Lecturer in Computer Science Page 13
14 You can also use empty() as the stopping condition on a while loop to clear a vector and display its contents in reverse order: vector<int> v; for (int i = 0; i < 5; i++) { v.push_back(i); while (!v.empty()) { cout << v.back() << endl; v.pop_back(); Sample run : What is the output of the following program vector<int> v; for (int i = 0; i < 5; i++) v.push_back(i); v.clear(); while (!v.empty()) { cout << v.back() << endl; v.pop_back(); Spring 2018 Husain Gholoom Lecturer in Computer Science Page 14
15 The begin() function returns an iterator pointing to the first element in the vector. The end() function returns an iterator pointing to the last element in the vector The erase() function either deletes the element at location loc, or deletes the elements between start and end (including start but not including end). The return value is the element after the last element erased. For Example vector<char> alphavector; for (int i = 0; i < 10; i++) alphavector.push_back(i + 65); for (int i = 0; i < alphavector.size(); i++) cout << alphavector[i]; cout << endl; // use erase to remove all but the first two and last three elements // of the vector alphavector.erase(alphavector.begin() + 2, alphavector.end() - 3); for (int i = 0; i < alphavector.size(); i++) cout << alphavector[i]; Sample run: ABCDEFGHIJ ABHIJ Spring 2018 Husain Gholoom Lecturer in Computer Science Page 15
16 The max_size() function returns the maximum number of elements that the vector can hold or the maximum length that a vector can hold. Is the theoretical maximum number of items that could be put in your vector. On a 32- bit system, you could in theory allocate 4Gb == 2^32 which is 2^32 char values, 2^30 int values or 2^29 double values. The max_size() function should not be confused with the size() or capacity() functions, which return the number of elements currently in the vector and the number of elements that the vector will be able to hold before more memory will have to be allocated, respectively. For Example vector<int> v1(20); for (int i = 0; i < 10; i++) v1.push_back(i); cout << "size\t" << v1.size() << endl; cout << "capacity\t" << v1.capacity() << endl; cout << "max size\t" << v1.max_size(); Sample run: size 30 capacity 40 max size Spring 2018 Husain Gholoom Lecturer in Computer Science Page 16
17 The insert() function either: inserts val before loc, returning an iterator to the element inserted, inserts num copies of val before loc, or inserts the elements from start to end before loc. For Example vector<int> vec(8); for (size_t i = 0; i < 5; i++) vec[i] = i + 1; cout << "Before insert\t"; Sample run: Before insert After insert After 2nd insert Size of the vector is??????? for (size_t i = 0; i < 8; i++) cout << vec[i] << " "; vec.insert(vec.begin() + 2, 10); cout << "\nafter insert\t"; for (size_t i = 0; i < 8; i++) cout << vec[i] << " "; vec.insert(vec.begin(), 5, 500); cout << "\nafter 2nd insert\t"; for (size_t i = 0; i < 8; i++) cout << vec[i] << " "; cout <<"\nsize of the vector is " << vec.size(); Spring 2018 Husain Gholoom Lecturer in Computer Science Page 17
18 Here is another example of the insert() function. In this code, insert() is used to append the contents of one vector onto the end of another: vector<int> v1; v1.push_back(0); v1.push_back(1); v1.push_back(2); v1.push_back(3); vector<int> v2; v2.push_back(5); v2.push_back(6); v2.push_back(7); v2.push_back(8); cout << "Before, v2 is: \t"; for (int i = 0; i < v2.size(); i++) { cout << v2[i] << " "; cout << endl; v2.insert(v2.end(), v1.begin(), v1.end()); cout << "After, v2 is: \t"; for (int i = 0; i < v2.size(); i++) { cout << v2[i] << " "; Sample run : Before, v2 is: After, v2 is: Spring 2018 Husain Gholoom Lecturer in Computer Science Page 18
19 The size() function returns the number of elements in the current vector. The function resize() changes the size of the vector to size. If val is specified then any newly- created elements will be initialized to have a value of val. vector<double> student_marks; // no size specified: vector contains // no elements int num_students; cout << "\nnumber of students: " << flush; cin >> num_students; student_marks.resize(num_students); cout << "\n" << student_marks.size(); cout << "\n\nnew Number of students: " << flush; cin >> num_students; student_marks.resize(num_students); cout << "\n" << student_marks.size(); cout << "\n\nnew Number of students: " << flush; cin >> num_students; student_marks.resize(num_students); cout << "\n" << student_marks.size(); Sample run : Number of students: 3 3 New Number of students: 5 5 New Number of students: 7 7 Spring 2018 Husain Gholoom Lecturer in Computer Science Page 19
20 The swap() function exchanges the elements of the current vector with those of from. For Example vector<string> v1; v1.push_back("i'm in v1!"); vector<string> v2; v2.push_back("and I'm in v2!"); v1.swap(v2); cout << "The first element in v1 is cout << "The first element in v2 is " << v1.front() << endl; " << v2.front() << endl; Sample run: The first element in v1 is And I'm in v2! The first element in v2 is I'm in v1! Spring 2018 Husain Gholoom Lecturer in Computer Science Page 20
21 Vector & Parameter passing (for large objects) Call by value is the default int findmax(vector<int> a); Problem: lots of copying if a is large Call by reference can be used int findmax(vector<int> & a); Problem: may still want to prevent changes to a Call by constant reference: int findmax(const vector<int> & a); the const won t allow a to be changed Spring 2018 Husain Gholoom Lecturer in Computer Science Page 21
22 Example : /* */ Suppose that we want to input an unknown number of numbers and then print them out forwards and then backwards, using a vector. We will push ints onto the back of a vector called v. We will then print each item in v in turn. We then will print the vector backwards. Other operations will be also used such erase, copy, find the size. etc. You can download the code from [ Vector.cpp ] but here are the highlights. First we must declare the facilities we want to use #include<iostream> void print( const vector<int>& ) ;//utility function outputs a vector of ints void print_backwards( const vector<int> &); /*Then we describe the main program: */ int main() { vector<int> v; vector<int> v1; int number; cout <<"Input some numbers and then end the input any other char "; while(cin>>number){ v.push_back(number); //while(more) print(v); print_backwards(v); // Test to see if v is empty cout <<" Is the Vector v Empty " << v.empty() << endl <<endl ; // Find how many items are in v cout <<" Size of the Vector v is " << v.size() << endl << endl ; // Access the i'th item safely: // What happens if value of i > size of the array vector int i = 3; cout << " Access the i th Item " <<v.at(i) << endl << endl; // get the back item of v: cout <<" Back Item of the Vector v is " << v.back() << endl << endl ; // change the back item: v.back() = ( v.at(2) ); cout <<" Back Item of the Vector v after the change is " << v.back() << endl << endl ; Spring 2018 Husain Gholoom Lecturer in Computer Science Page 22
23 // Assign a copy of v to v1 : v1 = v; print(v1); // end main // Remove First element of the vector. v1.erase( v1.begin( ) ); print(v1); // Remove range of element of the vector. v1.erase( v1.begin( ) + 1, v1.begin( ) + 5 ); print(v1); /* The two procedures that print out the data: */ void print( const vector<int>& a) { cout << endl; cout << " "<<endl; for(int i=0; i<a.size(); i++) cout << a[i] << " "; //print cout << endl; cout << " "<<endl; void print_backwards( const vector<int> &a) { cout << " "<<endl; for(int i=a.size() - 1; i>=0; i--) cout << a[i] << " "; cout << endl; cout << " "<<endl; //print_backwards Spring 2018 Husain Gholoom Lecturer in Computer Science Page 23
24 Sample Run Input some numbers and then end the input any other char # Is the Vector v Empty 0 Size of the Vector v is 9 Access the i th Item 4 Back Item of the Vector v is 9 Back Item of the Vector v after the change is Spring 2018 Husain Gholoom Lecturer in Computer Science Page 24
25 Example using vector resize // Read an unlimited number of ints with no attempts at error // recovery; fill the vector parameter with the data; its size // after the return tells how many items were read. void getints( vector<int> & array ) { int itemsread = 0; int inputval; cout << "Enter any number of integers: "; while( cin >> inputval ) { if( itemsread == array.size( ) ) array.resize( array.size( ) * ); array[ itemsread++ ] = inputval; array.resize( itemsread ); int main( ) { vector<int> array; getints( array ); for( int i = 0; i < array.size( ); i++ ) cout << array[ i ] << endl; Sample Run Enter any number of integers: / Spring 2018 Husain Gholoom Lecturer in Computer Science Page 25
26 Multidimensional Arrays Multidimensional arrays, the most common multidimensional arrays, are used to store information that we normally represent in table form. Twodimensional arrays, like one-dimensional arrays, are homogeneous. This means that all of the data in a two-dimensional array is of the same type. Examples of applications involving two-dimensional arrays include: a seating plan for a room (organized by rows and columns), a monthly budget (organized by category and month), and a grade book where rows might correspond to individual students and columns to student scores. Multidimensional array: an array that is accessed by more than one index Multidimensional arrays can be declared and initialized as follows: int A[3][4] = {{8, 2, 6, 5, //row 0 {6, 3, 1,0, //row 1 {8, 7, 9, 6; //row 2 int A[3][4]; // 3 rows, 4 columns cout >> A[0][0] ; // displays 8 on screen Spring 2018 Husain Gholoom Lecturer in Computer Science Page 26
27 There are no first-class versions of this in the STL Most books define this as a matrix. The primitive version can have more than 2 dimensions. Two- Dimensional Arrays as Function Parameters As with one-dimensional arrays, a two-dimensional array is automatically passed as a pass-by-reference parameter void displayarray(int A[][4], int x) { for ( int i = 0 ; i < x ; i++) { for ( int j = 0 ; j < 4 ; j++) cout << A[i][j]<< "\t"; cout <<endl; int A[3][4] = { { 8, 2, 6, 5, //row 0 { 6, 3, 1, 0, //row 1 { 8, 7, 9, 6 ; //row 2 displayarray(a,3); Spring 2018 Husain Gholoom Lecturer in Computer Science Page 27
28 Multidimensional vector array constructors You can create a 2D array by doing int a[5][7], but vector<int> a(5,7) won't create a 2D vector - it will create a 5-element vector full of 7s. Instead, you need to create a vector of vectors. Example int main() { // Example to create a 3 by 5 "matrix" using vector. // First, create a vector with 5 elements vector<int> v2(5, 99); // Then create a vector of 3 elements. // Each element is a copy of v2 //The space between the 2 '>' signs is necessary vector<vector<int> > _2dv(3, v2); // Print out the elements for (int i = 0; i < _2dv.size(); i++) { for (int j = 0; j < _2dv[i].size(); j++) cout << _2dv[i][j] << " "; cout << endl; Sample run Spring 2018 Husain Gholoom Lecturer in Computer Science Page 28
29 Passing 2d vector array to a function You can pass by value or by reference, or by pointer(not recommended). If you're passing to a function that doesn't change the contents, you can either pass by value, or by const reference. Example void matrixsize(vector<vector<int> > matrix); void populatematrix(vector<vector<int> > &matrix) ; void resizematrix(vector<vector<int> > &matrix) ; void printmatrix(vector<vector<int> > matrix); const int NO_OF_ROWS = 7; const int NO_OF_COLUMNS = 7; int main() { // Example to create a 7 by 7 "matrix" using vector. // First, create a vector with 0 elements vector<int> v2; // Then create a vector of 0 elements. // Each element is a copy of v2 //The space between the 2 '>' signs is necessary vector<vector<int> > _2dv(0, v2); Spring 2018 Husain Gholoom Lecturer in Computer Science Page 29
30 // Passing 2d vector array to functions matrixsize(_2dv); // display size the martrix resizematrix(_2dv); // resize the martrix printmatrix(_2dv); // display matrix content populatematrix(_2dv); // populate the matrix printmatrix(_2dv); // display the matrix void populatematrix(vector<vector<int> > & matrix) { for ( int i = 0 ; i < matrix.size() ; i++) for ( int j = 0 ; j < matrix.size() ; j++) matrix[i][j] = i+j; void matrixsize(vector<vector<int> > matrix) { cout <<"matrix size " << matrix.size() << endl; void resizematrix(vector<vector<int> > &matrix) { matrix.resize( NO_OF_ROWS, vector <int>( NO_OF_COLUMNS ) ); void printmatrix(vector<vector<int> > matrix){ matrix size 0 cout <<"\n\n"; for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix.size(); j++) cout << matrix[i][j] << " "; cout << endl; Spring 2018 Husain Gholoom Lecturer in Computer Science Page 30
31 Structure, Vector, and Array struct Soldier { int health; int ID; ; vector<soldier> army; for (int i = 0; i < 10; i++) { Soldier temp; temp.health = 100; temp.id = i; army.push_back(temp); // Accessing elements through the [] operator for (unsigned int i = 0; i < army.size(); i++) { cout << "Soldier ID = " << army[i].id << ", health = " << army[i].health << endl; Sample Run Soldier ID = 0, health = 100 Soldier ID = 1, health = 100 Soldier ID = 2, health = 100 Soldier ID = 3, health = 100 Soldier ID = 4, health = 100 Soldier ID = 5, health = 100 Soldier ID = 6, health = 100 Soldier ID = 7, health = 100 Soldier ID = 8, health = 100 Soldier ID = 9, health = 100 Spring 2018 Husain Gholoom Lecturer in Computer Science Page 31
Templates and Vectors
Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector
More informationContainers in C++ and Java
Containers in C++ and Java 1 1. Which of the following statements is true? a) Equality on the basis of reference implies equality on the basis of content. b) Equality on the basis of content implies equality
More informationFor example, let s say we define an array of char of size six:
Arrays in C++ An array is a consecutive group of memory locations that all have the same name and the same type. To refer to a particular location, we specify the name and then the positive index into
More informationTHE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming
THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming What the heck is STL???? Another hard to understand and lazy to implement stuff? Standard Template Library The standard template
More informationSTL: C++ Standard Library
STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms
More informationArrays. Arizona State University 1
Arrays CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 8 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More information7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology 8/23/2014. Arrays Hold Multiple Values
Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations Declared using
More informationSTL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms
STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed
More informationLecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1
Lecture 12 Log into Linux. Copy files on csserver in /home/hwang/cs215/lecture12/*.* Reminder: Practical Exam 1 is Wednesday 3pm-5pm in KC-267. Questions about Project 2 or Homework 6? Submission system
More informationPurpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures
C++ Review 1 Purpose of Review Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures 2 Class The Class defines the data structure
More informationComputer Science II Lecture 2 Strings, Vectors and Recursion
1 Overview of Lecture 2 Computer Science II Lecture 2 Strings, Vectors and Recursion The following topics will be covered quickly strings vectors as smart arrays Basic recursion Mostly, these are assumed
More informationChapter 7: Arrays Copyrig opy ht rig 2012 Pea e rson a Educa Educ ti a on, Inc I. nc
Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Arrays Hold Multiple Values Array variable that can store multiple values of the same type (aggregate type) Values are stored in adjacent memory locations
More information7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology
Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley
More informationCours de C++ Introduction
Cours de C++ Introduction Cécile Braunstein cecile.braunstein@lip6.fr Cours de C++ 1 / 20 Généralité Notes Interros cours 1/3 Contrôle TP 1/3 Mini-projet 1/3 Bonus (Note de Participation) jusqu à 2 points
More informationExam 3 Chapters 7 & 9
Exam 3 Chapters 7 & 9 CSC 2100-002/003 29 Mar 2017 Read through the entire test first BEFORE starting Put your name at the TOP of every page The test has 4 sections worth a total of 100 points o True/False
More informationTo declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows
Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful
More informationChapter 5. The Standard Template Library.
Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,
More informationSTRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY
STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY Objectives Declaration of 1-D and 2-D Arrays Initialization of arrays Inputting array elements Accessing array elements Manipulation
More informationCSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists
CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,
More informationC++ Arrays and Vectors
C++ Arrays and Vectors Contents 1 Overview of Arrays and Vectors 2 2 Arrays 3 2.1 Declaring Arrays................................................. 3 2.2 Initializing Arrays................................................
More informationLecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47
Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers
More informationCSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists
CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,
More informationType Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works
Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.
More informationData Structures CSci 1200 Test 2 Questions
Overview Data Structures CSci 1200 Test 2 Questions Test 2 will be held Thursday, March 10, 2010, 12:00-1:30pm, Darrin 308. No make-ups will be given except for emergency situations, and even then a written
More informationVector. Vector Class. class Vector { public: typedef unsigned int size_type;
Vector Arrays in C++ must be pre-allocated to accomodate the maximum number of elements. Should an application attempt to add more than this number, the program may abort, or alter storage of adjacent
More informationChapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:
Chapter 8 Arrays and Strings Objectives In this chapter, you will: Learn about arrays Declare and manipulate data into arrays Learn about array index out of bounds Learn about the restrictions on array
More informationC++ 프로그래밍실습. Visual Studio Smart Computing Laboratory
C++ 프로그래밍실습 Visual Studio 2015 Templates & STL Contents Exercise Practice1 Templates & STL Practice 1-1 Template Classes #include using namespace std; template class Point { private:
More informationGridKa School 2013: Effective Analysis C++ Standard Template Library
GridKa School 2013: Effective Analysis C++ Standard Template Library Introduction Jörg Meyer, Steinbuch Centre for Computing, Scientific Data Management KIT University of the State of Baden-Wuerttemberg
More informationBITG 1113: Array (Part 1) LECTURE 8
BITG 1113: Array (Part 1) LECTURE 8 1 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D)
More informationLinked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list
Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is
More informationContainer Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11
Di erent Kinds of Containers Container Notes A container is an object that stores other objects and has methods for accessing the elements. There are two fundamentally di erent kinds of containers: Sequences
More informationCSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators
CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators Review from Lecture 7 Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors
More informationIn this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021
Chapter 8 In this chapter, you will learn about: An Array Type for Strings The Standard string Class Vectors The C Language Representation of Strings (C-Strings) The C-String Variable: Array of Characters
More informationAlgorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14
Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer Science, UCSB Administra:ve Turn in Homework #12 Homework #13 is due Tuesday Lab
More informationLecture on pointers, references, and arrays and vectors
Lecture on pointers, references, and arrays and vectors pointers for example, check out: http://www.programiz.com/cpp-programming/pointers [the following text is an excerpt of this website] #include
More information(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.
CS 7A - Fall 2016 - Midterm 1 10/20/16 Write responses to questions 1 and 2 on this paper or attach additional sheets, as necessary For all subsequent problems, use separate paper Do not use a computer
More informationData types. CISC 1600/1610 Computer Science I. Array syntax. Memory allocation. Zero-indexing 4/4/2016. Arrays
4/4/6 CISC 6/6 Computer Science I rrays Professor Daniel Leeds dleeds@fordham.edu JMH 38 Data types Single pieces of information one integer int one symbol char one truth value bool Multiple pieces of
More informationCSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators
Review from Lecture 7 CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors
More informationPIC 10A. Final Review
PIC 10A Final Review Final exam Thursday, December 18, 2014 8:00 AM - 11:00 AM MS 5200. In our usual class room. (Verify on my.ucla.edu!!) The final exam is worth 30% of your grade, same weight as 2 midterms.
More informationBITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)
BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional
More informationG52CPP C++ Programming Lecture 18
G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know
More informationModule 9. Templates & STL
Module 9 Templates & STL Objectives In this module Learn about templates Construct function templates and class templates STL 2 Introduction Templates: enable you to write generic code for related functions
More informationCS201 (Intro. to Computing) Sample Questions & Solutions for the FINAL Exam
CS201 (Intro. to Computing) Sample Questions & Solutions for the FINAL Exam Those questions do not imply any favorite subject or question type for the questions in the actual exam Please also review recitation
More informationData Structures Lecture 3 Order Notation and Recursion
Data Structures Lecture 3 Order Notation and Recursion 1 Overview The median grade.cpp program from Lecture 2 and background on constructing and using vectors. Algorithm analysis; order notation Recursion
More informationC++ Programming Fundamentals
C++ Programming Fundamentals 205 Elvis C. Foster Lecture 08: Working with Vectors In lectures 5 and 6, it was established that C++ allows you to create and manage a dynamic list by declaring the list as
More informationCSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists
Review from Lecture 8 CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators,
More informationSixth lecture; classes, objects, reference operator.
Sixth lecture; classes, objects, reference operator. 1 Some notes on the administration of the class: From here on out, homework assignments should be a bit shorter, and labs a bit longer. My office hours
More informationTopics. bool and string types input/output library functions comments memory allocation templates classes
C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers
More informationComputer Science II CSci 1200 Lecture 8 Iterators; Programming Examples
Computer Science II CSci 1200 Lecture 8 Iterators; Programming Examples Test 1 102 total points on the test. Therefore, your score is out of 102. Class average: 89.6 / 102 Distribution: Solutions are posted
More informationLinked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list
Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is
More informationVectors and Pointers CS 16: Solving Problems with Computers I Lecture #13
Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13 Ziad Matni Dept. of Computer Science, UCSB Announcements Midterm grades will be available on Tuesday, 11/21 If you *need* to know
More informationArrays array array length fixed array fixed length array fixed size array Array elements and subscripting
Arrays Fortunately, structs are not the only aggregate data type in C++. An array is an aggregate data type that lets us access many variables of the same type through a single identifier. Consider the
More informationSSE2034: System Software Experiment 3
SSE2034: System Software Experiment 3 Spring 2016 Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu STL Collection Types Template based set of collection
More informationPolymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.
Session 4 - Genericity, Containers Polymorphism Code that works for many types. Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson)
More informationCS2255 HOMEWORK #1 Fall 2012
CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The
More informationCSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array
Lesson Outcomes At the end of this chapter, student should be able to: Define array Understand requirement of array Know how to access elements of an array Write program using array Know how to pass array
More informationTemplate based set of collection classes STL collection types (container types)
STL Collection Types Template based set of collection classes STL collection types (container types) Sequences vector - collection of elements of type T list - doubly linked list, only sequential access
More informationuse static size for this buffer
Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation
More informationCSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors
Announcements CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors HW 1 is available on-line through the website (on the Calendar ). Be sure to read through this information as you start
More informationArrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors
Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8
More informationWhat will happen if we try to compile, link and run this program? Do you have any comments to the code?
1 # include < iostream > 2 3 int main () 4 { 5 std :: cout
More informationPIC 10A. Lecture 19: More about Vectors
PIC 10A Lecture 19: More about Vectors Passing vectors to functions We have already seen how to pass vectors to functions. However, the method we have used has some disadvatages. We have passed vectors
More informationChapter 01 Arrays Prepared By: Dr. Murad Magableh 2013
Chapter 01 Arrays Prepared By: Dr. Murad Magableh 2013 One Dimensional Q1: Write a program that declares two arrays of integers and fills them from the user. Then exchanges their values and display the
More informationCS197c: Programming in C++
CS197c: Programming in C++ Lecture 2 Marc Cartright http://ciir.cs.umass.edu/~irmarc/cs197c/index.html Administration HW1 will be up this afternoon Written assignment Due in class next week See website
More information19.1 The Standard Template Library
Chapter 19: The Template Library From a review of Effective STL : 50 Specific Ways to Improve Your Use of the Standard Template Library by ScottMeyers: It s hard to overestimate the importance of the Standard
More informationAgenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures
The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF
More informationcalling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!
Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns
More informationC++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections
C++ Programming Chapter 6 Arrays and Vectors Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics
More informationFunction Templates. Consider the following function:
Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But
More informationCSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions
CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions 1. You are given a map that associates strings with lists of strings. The definition is: map words; Write
More informationDYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY
DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY Pages 800 to 809 Anna Rakitianskaia, University of Pretoria STATIC ARRAYS So far, we have only used static arrays The size of a static array must
More informationAbstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221
Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221 Abstract Data Type (ADT) Def. a collection of related data items together with an associated set of operations e.g. whole numbers
More informationCS11 Advanced C++ Spring 2018 Lecture 2
CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are
More informationCSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation
Today CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation Another vector operation: pop back Erasing items from vectors is inefficient! Iterators and iterator operations
More informationCopyright 2003 Pearson Education, Inc. Slide 1
Copyright 2003 Pearson Education, Inc. Slide 1 Chapter 11 Strings and Vectors Created by David Mann, North Idaho College Copyright 2003 Pearson Education, Inc. Slide 2 Overview An Array Type for Strings
More informationBITG 1113: Array (Part 2) LECTURE 9
BITG 1113: Array (Part 2) LECTURE 9 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of C-strings (character arrays) 2. Use C-string functions 3. Use
More informationLecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)
Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of
More informationComputer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];
Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data
More informationCSC 2400: Computer Systems. Arrays and Strings in C
CSC 2400: Computer Systems Arrays and Strings in C Lecture Overview Arrays! List of elements of the same type Strings! Array of characters ending in \0! Functions for manipulating strings 1 Arrays: C vs.
More informationC++: Overview and Features
C++: Overview and Features Richard Newman r.newman@rdg.ac.uk Room CS127 2003-12-11 Programming & Design, 2003 1 Introduction You have: used streams seen how classes are used seen some C++ code Today: good
More informationChapter 7 Array. Array. C++, How to Program
Chapter 7 Array C++, How to Program Deitel & Deitel Spring 2016 CISC 1600 Yanjun Li 1 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory
More informationG52CPP C++ Programming Lecture 18. Dr Jason Atkin
G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that
More informationData Types (C/C++) Structures
Data Types (C/C++) Scalar (or Basic) Data Types (atomic values) o Arithmetic types Integers short, int, long char, bool Floating points float, double, long double Composite (or Aggregate) Types: o Arrays:
More informationCSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists
Review from Lecture 8 CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately, erasing items
More informationPOINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory
More informationl Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)
Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between
More informationSequential Containers. Ali Malik
Sequential Containers Ali Malik malikali@stanford.edu Game Plan Recap Overview of STL Sequence Containers std::vector std::deque Container Adapters Announcements Recap getline vs >> Bug favnum = fullname
More informationPrinciples of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns
Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns What is an array? Pointers Memory issues The name of the array is actually a memory address. You can prove this by trying to print
More informationPatterns: Working with Arrays
Steven Zeil October 14, 2013 Outline 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates
More informationthe Queue queue ADT using the STL queue designing the simulation simulation with STL queue using STL list as queue using STL vector as queue
the Queue 1 The Queue Abstract Data Type queue ADT using the STL queue 2 Simulating a Printer Queue designing the simulation simulation with STL queue 3 adapting STL list and vector using STL list as queue
More informationTest 2: CPS Owen Astrachan. November 17, Name: Honor code acknowledgement (signature)
Test 2: CPS 53.2 Owen Astrachan November 17, 1993 Name: Honor code acknowledgement (signature) Problem 1 value 12 pts. grade Problem 2 16 pts. Problem 3 10 pts. Problem 4 13 pts. Problem 5 14 pts. TOTAL:
More informationComputer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:
Computer Department Program: Computer Midterm Exam Date : 19/11/2016 Major: Information & communication technology 1 st Semester Time : 1 hr (10:00 11:00) Course: Introduction to Programming 2016/2017
More informationChapter 17: Linked Lists
Chapter 17: Linked Lists 17.1 Introduction to the Linked List ADT Introduction to the Linked List ADT Linked list: set of data structures (nodes) that contain references to other data structures list head
More information6. User Defined Functions I
6 User Defined Functions I Functions are like building blocks They are often called modules They can be put togetherhe to form a larger program Predefined Functions To use a predefined function in your
More informationCS 103 Lab 6 - Party Like A Char Star
1 Introduction In this lab you will implement a "hangman" game where the user is shown blanks representing letter of a word and then tries to guess and fill in the letters with a limited number of guesses.
More informationCS242 COMPUTER PROGRAMMING
CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing
More informationGeneral Advise: Don t reinvent the wheel
General Advise: Don t reinvent the wheel Use libraries: Discover the available open source libraries for your application Examples: STL, boost, thrust libraries Info on C++ and STL: http://www.cplusplus.com/reference,
More informationComputer Science II CSci 1200 Test 1 Overview and Practice
Computer Science II CSci 1200 Test 1 Overview and Practice Overview Test 1 will be held Tuesday, February 13, 2007, 2:00-3:30pm, West Hall Auditorium. No make-ups will be given except for emergency situations,
More informationCSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion
CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion Review from Lectures 5 & 6 Arrays and pointers, Pointer arithmetic and dereferencing, Types of memory ( automatic, static,
More informationReview Questions II KEY
CS 102 / ECE 206 Spring 2011 Review Questions II KEY The following review questions are similar to the kinds of questions you will be expected to answer on Exam II (April 7), which will focus on LCR, chs.
More information