더북(TheBook)

list와 마찬가지로 forward_list 컨테이너에도 sort()merge() 멤버가 있다. remove(), remove_if(), unique() 연산도 있고, 이들 연산도 list 컨테이너의 연산과 같다. forward_list 컨테이너가 실제로 동작하는 예제로 실습해보자. 이번에는 forward_list 컨테이너에 사각형 상자를 표현한 Box 타입 객체를 저장할 것이다. Box 클래스의 헤더 파일부터 정의하자.

// Box.h
// Ex2_06에서 사용할 Box 클래스 정의
#ifndef BOX_H
#define BOX_H
#include <iostream>                // 표준 스트림
#include <utility>                 // 비교 연산자 템플릿
using namespace std::rel_ops;      // 비교 연산자 템플릿 네임스페이스
 
class Box
{
private:
  size_t length {};
  size_t width {};
  size_t height {};
 
public:
  explicit Box(size_t l = 1, size_t w = 1, size_t h = 1) : length {l}, width {w}, height {h} {}
  double volume() const { return length*width*height; }
  bool operator<(const Box& box) { return volume() < box.volume(); }
  bool operator==(const Box& box) { return length == box.length&& width == box.width&&height ==
box.height; }
 
  friend std::istream& operator>>(std::istream& in, Box& box);
  friend std::ostream& operator<<(std::ostream& out, const Box& box);
};
 
inline std::istream& operator>>(std::istream& in, Box& box)
{
  std::cout << “Enter box length, width, & height separated by spaces - Ctrl+Z to end: “;
  size_t value;
  in >> value;
  if (in.eof()) return in;
 
  box.length = value;
  in >> value;
  box.width = value;
  in >> value;
  box.height = value;
  return in;
}
 
inline std::ostream& operator<<(std::ostream& out, const Box& box)
{
  out << “Box(” << box.length << ”,” << box.width << ”,” << box.height << ”) “;
  return out;
}
#endif
 

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.