Vector.md (1355B)
1 # Vector (C++) 2 3 **Definition:** Vectors in c++ are dynamically allocated arrays that use the heap instead of the stack. 4 5 Vectors are generally preferred to integer arrays because they can manage their own memory, be resized, and don't have to have a known size at compile time. 6 7 Here is some code that illustrates the properties of them: 8 9 ```cpp 10 11 #include "vector" 12 #include "iostream" 13 14 auto makeVec(){ 15 std::vector<int> vec = std::vector<int>(); 16 for(int i = 0 ; i < 1000; ++i){ 17 vec.push_back(i); 18 } 19 return vec; 20 } 21 22 void sideEffectTest(std::vector<int>* vec){ 23 for(int i = 0 ; i < 1000; ++i){ 24 vec->at(i) = 1; 25 } 26 } 27 28 int main(){ 29 30 for(int i = 0 ; i < 1000; ++i){ 31 auto vec = makeVec(); 32 for(int i = 0 ; i < 1000; ++i){ 33 //std::cout << vec.at(i) << std::endl; 34 } 35 } 36 37 while(true){ 38 auto vec = makeVec(); 39 sideEffectTest(&vec); 40 for(int i = 0 ; i < 1000; ++i){ 41 std::cout << vec.at(i) << std::endl; 42 } 43 } 44 45 return 0; 46 } 47 48 ``` 49 50 As we can see, vectors can be returned and passed around by value (default) and when this is done side effects don't impact the original vector. If we pass by reference either with a pointer or by specifying the input parameter as std::vector<int>& (this is the preferred way), we can then make changes to the input vector while still having memory managed for us automatically, as shown in the final while(true) loop.