add vector class

This commit is contained in:
Shayan Abyar 2024-06-11 08:23:24 +03:30
commit 0e1d4e3aad
1 changed files with 136 additions and 0 deletions

136
VecbyClass.cpp Normal file
View File

@ -0,0 +1,136 @@
#include<iostream>
using namespace std;
template<typename T>
class Vector {
private:
int size=0;
int capacity=1;
T* arr;
public:
Vector(int size_array,T* a){
size=size_array;
capacity=size*2;
arr=new T[capacity];
for (int i = 0; i < size; ++i) {
arr[i] = a[i];
}
}
Vector(){
arr= new T[capacity];
}
~Vector(){
delete[]arr;
}
void push_back(T data){
if (size==capacity){
T*temp = new T[capacity*2];
for (int i=0;i<size;i++){
temp[i]=arr[i];
}
delete[]arr;
arr=temp;
capacity*=2;
}
arr[size]=data;
// cout<<endl;
size++;
}
void pop_back(){
size-=1;
T* temp= new T[capacity];
for (int i;i<size;i++){
temp[i]=arr[i];
}
delete[]arr;
arr=temp;
}
T &get(int index){
// cout<<" a ";
return arr[index];
}
int get_size(){
return size;
}
void resize(int new_size){
T default_var;
if (new_size<size){
T* temp= new T[new_size];
for (int i=0;i<new_size;i++){
temp[i]=arr[i];
}
delete[]arr;
arr=temp;
}
else{
T* temp= new T[new_size];
for (int i=0;i<new_size;i++){
temp[i]=arr[i];
}
delete[]arr;
arr=temp;
}
capacity=2*new_size;
size=new_size;
}
///
int get_capacity(){
return capacity;
}
T& operator[](int a){return arr[a];}
};
// template<typename T>
// std::ostream& operator<<(std::ostream& out , Vector<T > b)
// {
// for (int i=0;i<b.get_size();i++){
// out << b[i] <<",";
// }
// return out;
// }
int main(){
int myarray[]={};
Vector<int> vec = Vector<int> ();
Vector<string> vec1 = Vector<string> ();
cout<<endl;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec[2]=4;
// vec.push_back(4);
// cout<<vec;
for (int i=0;i<vec.get_size();i++){
cout << vec[i] <<" ";
}
// vec.pop_back();
// for (int i=0;i<vec.get_size();i++){
// cout << vec[i] <<" ";
// }
// vec1.push_back("ali");
// vec1.push_back("o");
// for (int i=0;i<vec1.get_size();i++){
// cout << vec1[i] <<" ";
// }
// vec1.push_back("p");
// vec1.push_back("hello");
// // vec1.pop_back();
// vec1.resize(8);
// for (int i=0;i<vec1.get_size();i++){
// cout << vec1[i] <<" ";
// }
return 0;
}