Ysoroko/cpp_module_08

WTF in ex02 begin()?

Closed this issue · 1 comments

iterator begin()
{
/*	std::vector<T>	v;
	T		top;
	iterato		ret;
	int		n = 0;
	while (!this->empty())
	{
		top = this->top();
		v.push_back(top);
		this->pop();
		n++;
	}
	this->push(v[n - 1]);
	n--;
	ret = &(this->top());
	while (n--)
		this->push(v[n]);
	return (ret);*/
	return (&this->top() - std::stack<T>::size());
}

Dear BarkalovAl,

Thank you for taking your time to file this issue.

However, if you consider a simple main function like this used with your suggested implementation, you will see that your code doesn't give the desired result:

#include "mutantstack.hpp"

int main()
{
	MutantStack<int> mstack;

	mstack.push(5); 
	mstack.push(17);
	std::cout << "Begin: " << *(mstack.begin()) << std::endl; // Should display 5 but displays 0 (value of 0 could be different on your system)
}

The desired behaviour is the reference taken from any other container in C++.
Here you can see the example with the vectors:

#include "mutantstack.hpp"

int main()
{
	std::vector<int> v;

	v.push_back(5);
	v.push_back(17);
	std::cout << "Begin: " << *(v.begin()) << std::endl; // Will display "Begin: 5"
	return (0);
} 

An alternative solution could be the following implementation:

iterator begin()
{
	return (&this->top() - std::stack<T>::size() + 1);
}

My approach here is in no way a reference for the best possible solution, but merely my personal take on the task when I was learning C++.

I am glad you thought of a better approach, but be careful because the one you suggested doesn't work.

I wish you best of luck in learning C++.
If you have any questions, don't hesitate to contact me.

Kind regards,
Yaro