2016-11-26 1 views
3

내 클래스 유형의 STL Vector를 이진 파일로 작성하고 읽으려고하지만 istream_iterator의 문제점을 이해하지 못합니다.
프로젝트 규칙은 Boost와 같은 타사 라이브러리와 동일한 텍스트 파일 을 사용할 수 없습니다.istream_iterator를 사용하여 사용자 정의 유형의 벡터 만들기

class Book{ 
    public: 
    Book(const std::vector<Book>& in_one_volumes,const std::string& title, 
    const std::string& author,const int pagecount,const int price,const std::string& date); 
    private: 
    std::vector<Book> inOneVolumes; 
    std::string title; 
    std::string author; 
    int pagecount; 
    int price; 
    std::string date; 
}; 

이 쓰기 방법 :

void writeBook(std::vector<Book> books) { 
    std::ofstream binOut("book.bin", std::ios::binary); 
    std::copy(books.begin(), books.end(), 
     std::ostream_iterator<Book>(binOut, "\n")); 
} 

그리고 내가 같이 읽고 싶은 :

std::vector<Book> readBooks() { 
    std::vector<Book> toReturn; 
    std::ifstream BinIn("book.bin", std::ios::binary); 
    std::istream_iterator<Book> file_iter(BinIn); 
    std::istream_iterator<Book> end_of_stream; 
    std::copy(file_iter, end_of_stream, std::back_inserter(toReturn)); 
    return toReturn;  
} 

Compiller 말한다 - 예약

은 Book.h입니다 : 사용 가능한 적절한 기본 생성자가 없습니다.

답변

3

std::istream_iterator<Book>operator>>(std::istream&, Book&)을 사용하여 데이터를 개체로 읽습니다. 이 operator>>은 기존의 Book 객체를 매개 변수로 요구하기 때문에 (데이터를 쓰려면) 반복기는 스트림에서 데이터를 덤프하기 전에 생성해야하며,이 경우 기본 생성자가 필요합니다.

Book 클래스에는 클래스가 없습니다. 문제를 해결하는 가장 쉬운 방법은 문제를 해결하는 것입니다.

이 옵션이없는 경우 (예 : 기본 생성자가 제공 할 수없는 불변 값을 보장하기 위해 Book) 기본 구성 가능하고 데이터를 통해 데이터를 채울 수있는 중간 데이터 전송 클래스를 도입 할 수 있습니다 operator>>이고, Book으로 변환 될 수 있습니다. 스케치 :

class TransferBook { 
public: 
    // To read data from stream 
    friend std::istream &operator>>(std::istream &in, TransferBook &dest); 

    // Conversion to Book. Use the non-default Book constructor here. 
    operator Book() const { 
    return Book(all the data); 
    } 

private: 
    // all the data 
}; 

... 

std::vector<Book> books; 
std::ifstream file; 

// Note that books contains Books and the iterator reads TransferBooks. 
// No Book is default-constructed, only TransferBooks are. 
std::copy(std::istream_iterator<TransferBook>(file), 
      std::istream_iterator<TransferBook>(), 
      std::back_inserter(books)); 

것은 확실히,이 방법은 다소 복잡하고 본질적으로 코드를 복제하고, 아마 Book 기본-생성자를주고 덜 번거 로움이있다. 그러나 Book을이 방법으로 변경할 수없는 경우 가능한 해결 방법입니다.

+0

대단히 감사합니다, 저를 도왔습니다! – Zulcom

관련 문제