[C++] CPP Module 08

J_JEON·2022년 12월 24일
0

CPP

목록 보기
9/9

CPP Module 08

  • 07과 같이 템플릿을 사용하지만 여태 사용하짐 못했던 STL(Container, Iterator, Algorithm)을 적극적으로 사용하여 실습

Sequential Container (iterator 존재 O)
→ std::vector<T>, std::deque<T>, std::list<T>, std::forward_list<T>

Adaptor Container (iterator 존재 X)
→ std::stack<T>, std::queue<T>, std::priority_queue<T>

ex00

  • 컨테이너에서 value를 찾아 iterator를 반환해주는 easyfind()함수를 작성
  • 이때 인자로 들어가는 컨테이너는 Sequential Container만 해당됨
  • template을 활용해 여러가지 컨테이너를 받을 수 있도록 함
  • std::find 활용해 value를 찾고 iterator를 반환
template <typename T>
typename T::iterator easyfind(T &container, int value)
{
	typename T::iterator iter;
	iter = std::find(container.begin(), container.end(), value);
	if (iter == container.end())
		throw InvalidValueException();
	else
		return (iter);
}

ex01

  • Span 클래스를 작성
  • 클래스 생성자에서 인자가 없다면 0개를 저장하는 빈 클래스 생성, unsigned int N을 받는다면 최대 N개의 정수를 저장할 수 있도록 생성해야 함
  • addNumber()를 사용해 정수를 추가할 수 있어야 함, 이때 최대 갯수를 초과했다면 exception throw
  • shortestSpan() 과 longestSpan()은 각각 클래스에 저장된 정수들 사이의 가장 작은 간격과 가장 큰 간격을 반환해 줌
class Span
{
	private:
			std::vector<int> _vec;
			unsigned int _size;
	public:
			Span();
			Span(unsigned int n);
			Span(const Span &s);
			Span &operator=(const Span &s);
			~Span();
			void addNumber(int num);
			void addRandom(unsigned int range);
			unsigned int shortestSpan();
			unsigned int longestSpan();
	class	OverSizeException : public std::exception
	{
		public:
			const char	*what() const throw();
	};

	class	NoSpanException : public std::exception
	{
		public:
			const char	*what() const throw();
	};
};

ex02

  • std::stack을 상속받는 MutantStack 클래스를 생성
  • stack에 존재하지않는 iterator를 사용할 수 있도록 작성
  • stack은 Sequential Container(vector, deque, list)를 바탕으로 생성됨 (default는 dequeue)
  • stack을 생성할때 사용된 바탕 컨테이너로 접근할 수 있는 stack의 c를 잘 활용 ( this->c.~ )
    typedef typename MutantStack<T>::stack::container_type::iterator iterator;
    typedef typename MutantStack<T>::stack::container_type::const_iterator const_iterator;
    typedef typename MutantStack<T>::stack::container_type::reverse_iterator reverse_iterator;
    typedef typename MutantStack<T>::stack::container_type::const_reverse_iterator const_reverse_iterator;

	iterator begin()
	{return(this->c.begin());}

	const_iterator begin() const
	{return(this->c.begin());}

	iterator end()
	{return (this->c.end());}

	const_iterator end() const
	{return (this->c.end());}

	reverse_iterator rbegin()
	{return (this->c.rbegin());}

	const_reverse_iterator rbegin() const
	{return (this->c.rbegin());}

	reverse_iterator rend()
	{return (this->c.rend());}

	const_reverse_iterator rend() const
	{return (this->c.rend());}
profile
늅늅

0개의 댓글