2014-04-23 2 views
1

set 반복자와 std::cout을 사용하면 다중 세트에 저장된 요소를 표시 할 수 있지만 학습 과정에서는 ostream_iterator을 사용하고 싶습니다. 그러면 내가 우둔한 것처럼 보입니다.
여기 내가했고, 무엇을 어떻게해야합니까 클래스가 클래스 학생ostream_iterator를 사용하여 객체의 속성을 표시하는 방법.

class Student 
{ 
private : 
    int age_; 
    std::string name_; 
    double marks_; 

public : 
    Student(); 

    Student(int age, string name, double marks): 
     age_(age), 
     name_(name), 
     marks_(marks) 
    { 
    } 

    int get_age() const 
    { 
     return age_; 
    } 

    std::string get_name() const 
    { 
     return name_; 
    } 

    double get_marks() const 
    { 
     return marks_; 
    } 

}; 

내가의 오름차순으로 멀티 설정에서 학생 클래스의 모든 개체를 저장 한 말을 가지고

일에 관심이 자신의 나이. 그 ostream_iterator 호출 할 때 할당되는 것 때문에 예를

class Compare 
{ 
public: 
    bool operator()(Student s1, Student s2) 
    { 
     return (s1.getage() < s2.getage()); 
    } 

}; 

// ... then somewhere ... 
std::multiset<Student, Compare > student_set; 
Student A21(21, " AVi", 49.5); 
Student A17(17, " BLA", 67.0); 
Student A57(57, " BLC", 41.0); 

bla bla bla ..... 
bla bla bla..... 

student_set.insert(A21); 
student_set.insert(A17); 
bla bla bla ..... 
bla bla bla..... 

는 지금, 나는 당신은 당신의 클래스 operator<<에 과부하가 필요

student.get_name() << student.get_age() << student.get_marks(); 

// no idea what to do here ?? 
std::ostream_iterator<????>output(std::cout, " "); 

std::copy(student_set.begin(), student_set.end(), output); 

답변

1

를 얻을 것이다 ostream_iterator 그래서 사용하여 모든 것을 표시하고 싶습니다. 이 같은

뭔가 :

std::ostream& operator<<(std::ostream& os, const Student& s) 
{ 
    return os << get_name() << get_age() << get_marks(); // needs some formatting 
} 

그리고 당신이 템플릿 인수로 Student와 반복자 구성 :

std::ostream_iterator<Student> output(std::cout, " "); 
+0

안녕 제록을, 그리고 기능 이상으로 정의 할 것인가? 클래스 학생이란 말인가요? – samprat

+0

@samprat 아니요, 무료 함수 여야합니다. 동시에 '친구'로 선언하면 클래스 내에서 정의 할 수 있지만 public get 함수가 있기 때문에 필연적 인 것은 아닙니다. – jrok

+0

Thnaks Mate, 약간의 사소한 질문이 1) 어떻게 ostream_iterator가 opertaor '<<'를 사용하고 그것을 구현해야한다는 것을 알 수 있습니까? 2) 위의 함수는 잘 작동합니다. s.get_name()을 제거했지만 s.get_name을 포함하면 "오류 : 연산자 '<<'가 피연산자와 일치하지 않습니다." – samprat

관련 문제