Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Understanding Vectors in C++: Definition, Access, and Manipulation, Exercises of Printing

An introduction to vectors in C++ programming, explaining their definition, initialization, accessing elements, and handling out-of-bounds elements. It includes exercises and examples to help students understand the concepts.

Typology: Exercises

2021/2022

Uploaded on 09/27/2022

myboy
myboy 🇺🇸

4.4

(72)

31 documents

1 / 52

Toggle sidebar

Related documents


Partial preview of the text

Download Understanding Vectors in C++: Definition, Access, and Manipulation and more Exercises Printing in PDF only on Docsity! Arrays and Vectors Victor Eijkhout, Susan Lindsey Fall 2021 last formatted: September 23, 2021 Vectors COE 322 - 2021 — – 2 Exercise 1 1. Take the above snippet, supply the missing header lines, compile, run. 2. Add a statement that alters the value of a vector element. Check that it does what you think it does. 3. Add a vector of the same length, containing odd numbers, which are the even values plus 1? You can base this off the file shortvector.cxx in the repository COE 322 - 2021 — – 5 3. Range over elements You can write a range-based for loop, which considers the elements as a collection. for ( float e : array ) // statement about element e for ( auto e : array ) // same, with type deduced by compiler Code: vector<int> numbers = {1,4,2,6,5}; int tmp_max = -2000000000; for (auto v : numbers) if (v>tmp_max) tmp_max = v; cout << "Max: " << tmp_max << " (should be 6)" << endl; Output [array] dynamicmax: Max: 6 (should be 6) COE 322 - 2021 — – 6 Exercise 2 Find the element with maximum absolute value in a vector. Use: vector<int> numbers = {1,-4,2,-6,5}; Hint: #include <cmath> .. absx = abs(x); COE 322 - 2021 — – 7 6. Accessing vector elements Square bracket notation (zero-based): Code: vector<int> numbers = {1,4}; numbers[0] += 3; numbers[1] = 8; cout << numbers[0] << "," << numbers[1] << endl; Output [array] assignbracket: 4,8 With bound checking: Code: vector<int> numbers = {1,4}; numbers.at(0) += 3; numbers.at(1) = 8; cout << numbers.at(0) << "," << numbers.at(1) << endl; Output [array] assignatfun: 4,8 Safer, slower. (Remember Knuth about optimization.) COE 322 - 2021 — – 10 7. Vector elements out of bounds Square bracket notation: Code: vector<int> numbers = {1,4}; numbers[-1] += 3; numbers[2] = 8; cout << numbers[0] << "," << numbers[1] << endl; Output [array] assignoutofboundbracket: 1,4 With bound checking: Code: vector<int> numbers = {1,4}; numbers.at(-1) += 3; numbers.at(2) = 8; cout << numbers.at(0) << "," << numbers.at(1) << endl; Output [array] assignoutofboundatfun: libc++abi.dylib: terminating with uncaught exception of type std:: out_of_range: vector Safer, slower. (Remember Knuth about optimization.) COE 322 - 2021 — – 11 8. Range over elements by reference Range-based loop indexing makes a copy of the vector element. If you want to alter the vector, use a reference: for ( auto &e : my_vector) e = .... Code: vector<float> myvector = {1.1, 2.2, 3.3}; for ( auto &e : myvector ) e *= 2; cout << myvector.at(2) << endl; Output [array] vectorrangeref: 6.6 (Can also use const auto& e to prevent copying, but also prevent altering data.) COE 322 - 2021 — – 12 Exercise 3 Find the location of the first negative element in a vector. Which mechanism do you use? COE 322 - 2021 — – 15 Exercise 4 Create a vector x of float elements, and set them to random values. Now normalize the vector in L2 norm and check the correctness of your calculation, that is, 1. Compute the L2 norm of the vector: ‖v‖ ≡ √∑ i v2i 2. Divide each element by that norm; 3. The norm of the scaled vector should now by 1. Check this. 4. Bonus: your program may be printing 1, but is it actually 1? Investigate. What type of loop are you using? COE 322 - 2021 — – 16 11. Indexing with pre/post increment Indexing in while loop and such: x = a.at(i++); /* is */ x = a.at(i); i++; y = b.at(++i); /* is */ i++; y = b.at(i); COE 322 - 2021 — – 17 14. Your first encounter with templates vector is a ‘templated class’: vector<X> is a vector-of-X. Code behaves as if there is a class definition for each type: class vector<int> { public: size(); at(); // stuff } class vector<float> { public: size(); at(); // stuff } Actual mechanism uses templating: the type is a parameter to the class definition. More later. COE 322 - 2021 — – 20 Dynamic behaviour COE 322 - 2021 — – 21 15. Dynamic vector extension Extend a vector’s size with push_back: Code: vector<int> mydata(5,2); mydata.push_back(35); cout << mydata.size() << endl; cout << mydata[mydata.size()-1] << endl; Output [array] vectorend: 6 35 Similar functions: pop_back, insert, erase. Flexibility comes with a price. COE 322 - 2021 — – 22 18. Filling in vector elements With subscript: vector<int> stat(LENGTH); /* ... */ for (int i=0; i<LENGTH; i++) stat[i] = i; You can also use new to allocate∗: int *stat = new int[LENGTH]; /* ... */ for (int i=0; i<LENGTH; i++) stat[i] = i; ∗Considered bad practice. Do not use. COE 322 - 2021 — – 25 19. Timing the ways of filling a vector Flexible time: 2.445 Static at time: 1.177 Static assign time: 0.334 Static assign time to new: 0.467 COE 322 - 2021 — – 26 Vectors and functions COE 322 - 2021 — – 27 22. Vector pass by reference If you want to alter the vector, you have to pass by reference: Code: void set0 ( vector<float> &v,float x ) { v.at(0) = x; } /* ... */ vector<float> v(1); v.at(0) = 3.5; set0(v,4.6); cout << v.at(0) << endl; Output [array] vectorpassref: 4.6 COE 322 - 2021 — – 30 Exercise 5 Revisit exercise 4 and introduce a function for computing the L2 norm. COE 322 - 2021 — – 31 23. Vector as function return You can have a vector as return type of a function. Example: this function creates a vector, with the first element set to the size: Code: vector<int> make_vector(int n) { vector<int> x(n); x.at(0) = n; return x; } /* ... */ vector<int> x1 = make_vector(10); // "auto" also possible! cout << "x1 size: " << x1.size() << endl; cout << "zero element check: " << x1 .at(0) << endl; Output [array] vectorreturn: x1 size: 10 zero element check: 10 COE 322 - 2021 — – 32 Exercise 7 Write functions random_vector and sort to make the following main program work: int length = 10; vector<float> values = random_vector(length); vector<float> sorted = sort(values); This creates a vector of random values of a specified length, and then makes a sorted copy of it. Instead of making a sorted copy, sort in-place (overwrite original data with sorted data): int length = 10; vector<float> values = random_vector(length); sort(values); // the vector is now sorted Find arguments for/against that approach. (Note: C++ has sorting functions built in.) COE 322 - 2021 — – 35 Vectors in classes COE 322 - 2021 — – 36 24. Can you make a class around a vector? You may want a class of objects that contain a vector. For instance, you may want to name your vectors. class named_field { private: vector<double> values; string name; The problem here is when and how that vector is going to be created. COE 322 - 2021 — – 37 26. Multi-dimensional vectors Multi-dimensional is harder with vectors: vector<float> row(20); vector<vector<float>> rows(10,row); // alternative: vector<vector<float>> rows(10); for ( auto &row : rows ) row = vector<float>(20); Create a row vector, then store 10 copies of that: vector of vectors. COE 322 - 2021 — – 40 27. Matrix class class matrix { private: vector<vector<double>> elements; public: matrix(int m,int n) { elements = vector<vector<double>>(m,vector<double>(n)); } void set(int i,int j,double v) { elements.at(i).at(j) = v; }; double get(int i,int j) { return elements.at(i).at(j); }; }; COE 322 - 2021 — – 41 Exercise 8 Write rows() and cols() methods for this class that return the number of rows and columns respectively. COE 322 - 2021 — – 42 Exercise 10 Add methods such as transpose, scale to your matrix class. Implement matrix-matrix multiplication. COE 322 - 2021 — – 45 29. Pascal’s triangle Pascal’s triangle contains binomial coefficients: Row 1: 1 Row 2: 1 1 Row 3: 1 2 1 Row 4: 1 3 3 1 Row 5: 1 4 6 4 1 Row 6: 1 5 10 10 5 1 Row 7: 1 6 15 20 15 6 1 Row 8: 1 7 21 35 35 21 7 1 Row 9: 1 8 28 56 70 56 28 8 1 Row 10: 1 9 36 84 126 126 84 36 9 1 where prc = ( r c ) = r ! c!(r − c)! . The coefficients can be computed from the recurrence prc = { 1 c ≡ 1 ∨ c ≡ r pr−1,c−1 + pr−1,c (There are other formulas. Why are they less preferable?) COE 322 - 2021 — – 46 Exercise 11 • Write a class pascal so that pascal(n) is the object containing n rows of the above coefficients. Write a method get(i,j) that returns the (i , j) coefficient. • Write a method print that prints the above display. • First print out the whole pascal triangle; then: • Write a method print(int m) that prints a star if the coefficient modulo m is nonzero, and a space otherwise. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * • The object needs to have an array internally. The easiest solution is to make an array of size n × n. • Your program should accept: 1. an integer for the size 2. any number of integers for the modulo; if this is zero, stop, otherwise print stars as described above. COE 322 - 2021 — – 47 Static arrays COE 322 - 2021 — – 50 Array creation C-style arrays still exist, { int numbers[] = {5,4,3,2,1}; cout << numbers[3] << endl; } { int numbers[5]{5,4,3,2,1}; numbers[3] = 21; cout << numbers[3] << endl; } but you shouldn’t use them. Prefer to use array class (not in this course) or span (C++20; very advanced) COE 322 - 2021 — – 51 Ranging You can range over static arrays same as for vector COE 322 - 2021 — – 52
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved