c-resources/CPlusPlus20ForProgrammers-m.../examples/vector/vector.h

55 lines
755 B
C
Raw Normal View History

2024-06-10 10:16:58 +00:00
#include <iostream>
namespace myspace {
template <typename T>
class vector{
public:
vector(){}
vector(int _N, T _Val);
~vector();
T operator[] (int i);
void resize();
int size(){
return N;
}
;
protected:
T** data;
int N;
};
template <typename T>
vector<T>::vector(int _N, T _Val ):N(_N){
data = new T*[N];
for (int i{0}; i < N; i++){
data[i] = new T(_Val);
}
}
template <typename T>
vector<T>::~vector(){
delete [] data;
}
template <typename T>
T vector<T>::operator[] (int i){
try {
if (i>=0 && i < N){
return *data[i];
}
else
throw(i);
}
catch(int i){
std::cout << "out of range, try to access "<< i << " out of " << N <<"\n";
exit(-1);
}
}
/// end of namespace ///
}