Skip to content

Instantly share code, notes, and snippets.

@egoarka
Created May 29, 2018 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egoarka/54a18003bc92e56aad42e3428cc9ae60 to your computer and use it in GitHub Desktop.
Save egoarka/54a18003bc92e56aad42e3428cc9ae60 to your computer and use it in GitHub Desktop.
simple iterator for container
#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