-
Notifications
You must be signed in to change notification settings - Fork 1
/
Vector.h
140 lines (134 loc) · 2.86 KB
/
Vector.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#ifndef VECTOR_H
#define VECTOR_H
using namespace std;
template <typename T>
class Vector {
T* arr;
int cs, ts;
public:
Vector(int t = 0) {
cs = t;
ts = 2 * t;
if (t == 0)
ts = 1;
arr = new T[ts];
}
Vector(int t, T init){
/// Intialise vector with init
cs = t;
ts = 2 * t;
arr = new T[ts];
for (int i = 0; i < cs; i++)
arr[i] = init;
}
Vector(vector<T> v) {
for(int i=0;i<v.size();i++)
push_back(v[i]);
}
void push_back(T data){
/// Push element on the back
if ((cs + 1) >= ts / 2) {
resize(ts);
ts *= 2;
}
arr[cs] = data;
cs++;
}
void pop_back(){
/// pop the last element in the vector
if (cs > 0)
cs--;
if (cs < ts / 4) {
resize(ts / 4);
ts /= 2;
}
}
T& back(){
return arr[cs - 1];
}
int size(){
return cs;
}
void resize(int newsize){
T* newarr = new T[2*newsize];
for (int i = 0; i < cs; i++) {
newarr[i] = arr[i];
}
delete[] arr;
arr = newarr;
}
int capacity(){
return ts;
}
// pos -ve,+ve>cs
// append two vectors
// vector slicing
T& operator[](int pos){
if(pos<0) {
return arr[cs-pos];
}
return arr[pos];
}
Vector operator[](string s) {
/// slice
string a="", b="";
int i;
for(i=0;s[i]!=':';i++)
a =a + s[i];
i++;
for(;i<s.length();i++)
b = b + s[i];
Vector<T> temp = Vector<T>();
for(int i=stoi(a);i<stoi(b);i++)
temp.push_back((*this)[i]);
return temp;
}
void append(Vector<T> v) {
for(int i=0;i<v.size();i++)
push_back(v[i]);
}
void append(vector<T> v) {
for(int i=0;i<v.size();i++)
push_back(v[i]);
}
Vector operator+(Vector<T> v) {
/// append two vectors
Vector<T> temp =Vector<T>(*this);
temp.append(v);
return temp;
}
void sortVec() {
/// sort vvector
sort(arr,arr+cs);
}/*
void splice() {
// delete element
}*/
///erase an element
void erase(int pos) {
int rpos;
if(pos<0)
rpos = cs-pos;
else
rpos = pos;
for(int i=rpos;i<cs-1;i++)
arr[i] = arr[i+1];
cs--;
}
void print() {
for(int i=0;i<cs;i++)
cout<<arr[i]<<" ";
}
void take_input(int start,int end) {
for(int i = start;i<end;i++) {
T temp;
cin>>temp;
push_back(temp);
}
}
};
#endif