|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +// #include <numeric> //std::iota |
| 4 | + |
| 5 | +// Compared to Arrays, Vectors are not memory efficient and time consuming to |
| 6 | +// access vector elements |
| 7 | + |
| 8 | +void Reverse(const std::vector<int>&); |
| 9 | +void PrintVectorVert (const std::vector<int>&); //Always pass by reference, |
| 10 | +//cz saves a lot of memory. also you always dont need a copy of vector |
| 11 | + |
| 12 | +int main(int argc, char const *argv[]) { |
| 13 | + |
| 14 | + // Initialize |
| 15 | + std::vector<int> nVect1; // Empty vector |
| 16 | + std::vector<int> nVect2 (100, 1); // A vector containing 100 items: All 1s. |
| 17 | + std::vector<int> nVect3 {100, 1}; // A vector containing 2 items: 100 and 1. |
| 18 | + std::vector<int> nVect4 (nVect3.begin(), nVect3.end()); //iterate nVect3 & fill |
| 19 | + std::vector<int> nVect5 (nVect4); // Copy nVect4 |
| 20 | + |
| 21 | + // Vector from ArraySum |
| 22 | + double dArr1[] = {1.0, 2.0, 3.0, 4.0}; |
| 23 | + std::vector<double> dVect6 (dArr1, dArr1 + sizeof(dArr1)/sizeof(*dArr1)); |
| 24 | + |
| 25 | + PrintVectorVert(nVect3); |
| 26 | + nVect3.push_back(11); //insert at the end of vector |
| 27 | + nVect3.push_back(22); |
| 28 | + nVect3.insert(nVect3.begin(), 999); //insert element before specified index |
| 29 | + nVect3.insert(nVect3.begin()+3, 555); |
| 30 | + std::cout << nVect3.at(2) << '\n'; //vector value at given index |
| 31 | + std::cout << nVect3.size() << '\n'; //vector size |
| 32 | + PrintVectorVert(nVect3); |
| 33 | + |
| 34 | + //Erase vector |
| 35 | + nVect3.erase(nVect3.begin()+2); //remove element at given index |
| 36 | + std::cout << "\nRemove 3rd vector element" << '\n'; |
| 37 | + PrintVectorVert(nVect3); |
| 38 | + Reverse(nVect3); |
| 39 | + |
| 40 | + // Clear vector |
| 41 | + // nVect3.erase(nVect3.begin(), nVect3.end()); //Erase everything |
| 42 | + nVect3.clear(); |
| 43 | + std::cout << "\nClear all vector element" << '\n'; |
| 44 | + std::cout << "Empty? " << nVect3.empty() << '\n'; |
| 45 | + |
| 46 | + |
| 47 | + // std::vector<int> nX(10); |
| 48 | + // std::iota(std::begin(nX), std::end(nX), 0);//range of 0 to 9; 0 starting num |
| 49 | + |
| 50 | + return EXIT_SUCCESS; |
| 51 | +} |
| 52 | + |
| 53 | + |
| 54 | +void PrintVectorVert (const std::vector<int>& nVect){ |
| 55 | + std::cout << "\n"; |
| 56 | + for(unsigned int i = 0; i < nVect.size(); i++) { |
| 57 | + std::cout << "v[" << i << "] = " << nVect[i] << '\n'; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +void Reverse(const std::vector<int>& nVect){ |
| 62 | + std::cout << "\nReveresed vector" << std::endl; |
| 63 | + for (size_t i = nVect.size(); i >0; i--) { //size_t: unsigned integer |
| 64 | + std::cout << "v[" << i-1 << "] = " << nVect[i-1] << '\n'; |
| 65 | + } |
| 66 | +} |
0 commit comments