diff --git a/C-Plus-Plus/README.md b/C-Plus-Plus/README.md index a4249df2..8cbac0fb 100644 --- a/C-Plus-Plus/README.md +++ b/C-Plus-Plus/README.md @@ -371,6 +371,7 @@ Format: -[Program name](name of the file) - [Tim sort](Tim_Sort.cpp) - [Twin prime](twin_prime.cpp) - [Value of Pi by Random Numbers](ValueOfPi.cpp) +- [vector data structure](vector.cpp) - [Word Break](Word-Break.cpp) - [BFS with path](BFS.cpp) - [Longest Path in DAG](Longest_path_in_DAG.cpp) diff --git a/C-Plus-Plus/vector.cpp b/C-Plus-Plus/vector.cpp new file mode 100644 index 00000000..b42ad30c --- /dev/null +++ b/C-Plus-Plus/vector.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +using namespace std; +/*Vectors are same as dynamic arrays with the ability to resize itself +automatically when an element is inserted or deleted*/ +void iterate_over_vector(auto start,auto end) +{ + for(auto i=start;i!=end;i++) + { + cout<<*i<<" "; + } + cout< &test,auto pos,int value) +{ + // O(n+m) + test.insert(pos,value); +} +void erase_element(vector &test,auto pos) +{ + // O(n) + test.erase(pos); +} + +bool is_vector_empty(vector &test) +{ + return test.empty(); +} + +int main() +{ + vector test; + test.push_back(5); // add 5 at the end O(1) + test.push_back(4); // added 4 after 5 O(1) + test.push_back(8); // Vector elements are placed in contiguous storage. + test.push_back(1); // O(1) + /* Iterate over vector + begin() – Returns an iterator pointing to the first element in the vector + end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector */ + + cout<<"Initial vector: "; + iterate_over_vector(test.begin(),test.end()); + cout<<"Size of vector: "<