Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef __STDVECTOR__
- #define __STDVECTOR__
- #include <iostream>
- using namespace std;
- template <typename T>
- class StdVector{
- private:
- T *buffer;
- unsigned int capacity;
- public:
- //Constructor.
- StdVector(){
- capacity=0;
- buffer=new T[capacity];
- }
- //Copy constructor.
- StdVector(const StdVector &asv){
- int i;
- capacity=asv.getCapacity();
- buffer=new T[asv.getCapacity()];
- for (i=0; i<capacity; i++){
- buffer[i]=asv[i];
- }
- }
- //Destructor.
- ~StdVector(){
- delete []buffer;
- }
- void push_back(T obj){
- StdVector oldSV(*this);
- int i;
- capacity++;
- delete []buffer;
- buffer=new T[capacity];
- for (i=0; i<oldSV.getCapacity(); i++){
- buffer[i]=oldSV[i];
- }
- buffer[i]=obj;
- };
- T getBuffer() const{
- if (capacity==0){
- throw exception();
- }
- return *buffer;
- };
- T &operator[](int index) const{
- if (index>=capacity){
- //Out of range.
- throw exception();
- }
- else{
- return buffer[index];
- }
- }
- StdVector &operator=(const StdVector &obj){
- capacity=obj.getCapacity();
- delete []buffer;
- buffer=new T[capacity];
- buffer=obj.getBuffer();
- return *this;
- }
- unsigned int getCapacity() const{
- return capacity;
- };
- };
- #endif
- int main(){
- try{
- StdVector<int> test;
- StdVector<string> test2;
- unsigned int i;
- test.push_back(5);
- test.push_back(4);
- test.push_back(3);
- test.push_back(2);
- test.push_back(1);
- test.push_back(0);
- test.push_back(-1);
- test.push_back(-2);
- test.push_back(-3);
- test.push_back(-4);
- test.push_back(-5);
- for (i=0; i<test.getCapacity(); i++){
- cout << test[i] << endl;
- }
- test2.push_back("Hello");
- test2.push_back(" ");
- test2.push_back("World");
- test2.push_back(".");
- cout << "---------------" << endl;
- for (i=0; i<test2.getCapacity(); i++){
- cout << test2[i];
- }
- cout << endl;
- }
- catch(...){
- cout << "Exception." << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement