Hello i need to implement a Set class(like in stl) using a vector.Here is my code that doesnt work corectly:
Code:
#include <iostream>
#include <vector>
template<class T>
class Set
{
std::vector<T> set;
typename std::vector<T>::iterator iter_m;
public:
class iterator;
friend class iterator;
class iterator
{
Set s;
typename std::vector<T>::iterator it;
public:
iterator(const Set& ss):s(ss)
{
it = s.set.begin();
}
// end sentinel
iterator(const Set& ss, bool):s(ss)
{
it = s.set.end();
}
iterator(const iterator& iter)
{
s = iter.s;
it = iter.it;
}
iterator()
{
//std::cout << "iterator()" << std::endl;
}
iterator& operator =(const iterator& iter)
{
if (&iter == this)
{
return *this;
}
s = iter.s;
it = iter.it;
return *this;
}
iterator& operator++()
{
it++;
return *this;
}
iterator& operator++(int)
{
return operator++();
}
iterator& operator--()
{
it--;
return *this;
}
iterator& operator--(int)
{
return operator--();
}
bool operator != (const iterator& cIter)
{
return this != &cIter;
}
T& operator*()
{
return *it;
}
T* operator->()
{
return it;
}
};
Set()
{
set.clear();
iter_m = set.begin();
}
void insert(const T& t)
{
iter_m = set.insert(iter_m, t);
std::cout << "dummy" << std::endl;
}
void insert(iterator it1, iterator it2)
{
set.insert(0, it1, it2);
}
void clear()
{
set.clear();
}
iterator begin()
{
return iterator(*this);
}
iterator end()
{
// call the end sentinel, meaning we create an iterator to the end of the vector
return iterator(*this, true);
}
int size()
{
return set.size();
}
T& operator [] (int index)
{
return set[index];
}
};
int main()
{
Set<int> mainSet;
mainSet.insert(70);
mainSet.insert(20);
mainSet.insert(50);
Set<int>::iterator it;
std::cout << "Size of set is: " << mainSet.size() << std::endl;
std::cout << "Begin: " << *(it = mainSet.begin()) << std::endl;
std::cout << "End: " << *(it = mainSet.end()) << std::endl;
for(int i = 0; i < mainSet.size(); i++)
{
std::cout << mainSet[i] << " ";
}
std::cout << std::endl;
}
If my input is: 70, 20, 50 then my output would look like this:
Code:
Size of set is: 3
Begin: 70
End: 25
0 20 50 25 70 20 50 0 0 135113 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
The end() function is not working coreclty and i dont know why it gives me so much numbers in output,some help would be apreciated.Thank you.