Created
October 19, 2021 17:52
-
-
Save Kabiirk/83ea7354a79f44e573ea00b4de135125 to your computer and use it in GitHub Desktop.
Common operation utilities for C++ Vectors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| void printVector(vector<int> vect){ | |
| cout<<"< "; | |
| for (unsigned int i: vect){ | |
| std::cout << i << ' '; | |
| } | |
| cout<<">"<<endl; | |
| } | |
| // Element-wise Multiplication of a vector with a Scalar | |
| vector<int> scalarMultipleVect(vector<int> vect, int scalar){ | |
| int n = vect.size(); | |
| int carry= 0; | |
| for(int i = 0; i<n; i++){ | |
| vect[i] = vect[i]*2 + carry; | |
| carry = 0; | |
| if(vect[i] >= 10){ | |
| carry = 1; | |
| vect[i] -= 10; | |
| if(i == n-1){ | |
| vect.push_back(carry); | |
| } | |
| } | |
| } | |
| return vect; | |
| } | |
| // Addition of 2 vectors where | |
| // Left has the least significant digit and Right has the Most signifigant digit | |
| // E.g. : | |
| // <0, 2, 4> represents 420 | |
| // <6, 5, 4, 3, 2, 1> represents 123,456 | |
| vector<int> addVect(vector<int> a, vector<int> b){ | |
| bignum sum = b; | |
| int carry = 0; | |
| for(int i = 0; i < sum.size(); i++){ | |
| if(i<a.size()){ | |
| sum[i] += a[i]; | |
| } | |
| sum[i] += carry; | |
| // handle overflow | |
| if(sum[i] >= 10){ | |
| carry = 1; | |
| sum[i] -= 10; | |
| } | |
| else{ | |
| carry = 0; | |
| } | |
| } | |
| // If Largest Digit overflowing | |
| if(carry != 0){ | |
| sum.push_back(carry); | |
| } | |
| return sum; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment