|
| 1 | +#include <iostream> |
| 2 | +#include <vector> //Don't forget to include this every time you need to use vectors |
| 3 | + |
| 4 | +int main() |
| 5 | +{ |
| 6 | + |
| 7 | + //Task 0: Create an empty vector V for integer elements |
| 8 | + std::vector< int > V{}; |
| 9 | + |
| 10 | + //Task 1: Add the elements 6, 10, 17 to V (in that order) |
| 11 | + V.push_back(6); //0 |
| 12 | + V.push_back(10);//1 |
| 13 | + |
| 14 | + std::cout <<"the size of V is " << V.size() << std::endl; |
| 15 | + |
| 16 | + V.push_back(17); //2 |
| 17 | + |
| 18 | + //Task 2: Print out the size of V |
| 19 | + |
| 20 | + std::cout <<"At the end the size is: " << V.size() << std::endl; |
| 21 | + //Task 3: Print out the element at index 1 of V |
| 22 | + std::cout << "The first element is " << V.at(0) << std::endl; |
| 23 | + std::cout << "The last element is " << V.at(2) << std::endl; |
| 24 | + size_t size{ V.size() }; |
| 25 | + std::cout << "Better way is " << V.at(size - 1) << std::endl; |
| 26 | + //std::cout << "bla " << V.at(30) << std::endl; |
| 27 | + V.push_back(333); |
| 28 | + V.push_back(42); |
| 29 | + //Task 4: Iterate over V and print out each element. |
| 30 | + for (int value : V) |
| 31 | + { |
| 32 | + std::cout << "the value is " << value << std::endl; |
| 33 | + } |
| 34 | + |
| 35 | + //Task 5: Use an indexing loop (that is, a C-style for-loop) to iterate |
| 36 | + // over each index of the vector. For each index, print the index |
| 37 | + // and the element at that index. |
| 38 | + // Note that the "natural" type for an index variable is "unsigned int". |
| 39 | + for (size_t i{ 0 }; i < V.size(); ++i) |
| 40 | + { |
| 41 | + std::cout << "the value at index " << i << " is " << V.at(i) << std::endl; |
| 42 | + } |
| 43 | + |
| 44 | + for (int i{ (int) V.size()-1}; i >= 0; --i) |
| 45 | + { |
| 46 | + std::cout << "the value at index " << i << " is " << std::endl; |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | + //Task 6: Add the value 187 to the end of V, then repeat steps 2-4 (by copying/pasting) |
| 51 | + |
| 52 | + unsigned int x{ 0 }; |
| 53 | + std::cout << "unsigned " << x << std::endl; |
| 54 | + --x; |
| 55 | + std::cout << "unsigned " << x << std::endl; |
| 56 | + |
| 57 | + return 0; |
| 58 | +} |
0 commit comments