Created
May 29, 2018 09:33
-
-
Save egoarka/54a18003bc92e56aad42e3428cc9ae60 to your computer and use it in GitHub Desktop.
simple iterator for container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
using namespace std; | |
template <typename T> | |
class Vector { | |
private: | |
T* data; | |
int _size; | |
public: | |
class iterator { | |
private: | |
T* ptr; | |
public: | |
iterator(T* aPtr): ptr(aPtr) {} | |
iterator operator++() { | |
ptr++; | |
return *this; | |
} | |
iterator operator--() { | |
ptr--; | |
return *this; | |
} | |
T& operator*() { | |
return *this->ptr; | |
} | |
T* operator->() { | |
return this->ptr; | |
} | |
bool operator==(const iterator& r) { | |
return this->ptr == r.ptr; | |
} | |
bool operator!=(const iterator& r) { | |
return this->ptr != r.ptr; | |
} | |
}; | |
Vector(int aSize): _size(aSize) { | |
this->data = new T[this->_size]; | |
} | |
~Vector() { | |
delete[] this->data; | |
} | |
int size() { | |
return this->_size; | |
} | |
T& operator[](int index) { | |
return this->data[index]; | |
} | |
iterator begin() { | |
return iterator(this->data); | |
} | |
iterator end() { | |
return iterator(this->data + this->_size); | |
} | |
}; | |
int main() { | |
Vector<int> vectorInt(3); | |
vectorInt[0] = 1; | |
vectorInt[1] = 2; | |
vectorInt[2] = 3; | |
for (Vector<int>::iterator i = vectorInt.begin(); i != vectorInt.end(); ++i) { | |
cout << *i << endl; | |
} | |
Vector<double> vectorDouble(3); | |
vectorDouble[0] = 1.1; | |
vectorDouble[1] = 2.2; | |
vectorDouble[2] = 3.3; | |
for (Vector<double>::iterator i = vectorDouble.begin(); i != vectorDouble.end(); ++i) { | |
cout << *i << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment