homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/homework_5.pdf · 온단어순으로출력하라....

17

Upload: others

Post on 04-Jul-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다
Page 2: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

5_1. 긴 문자열에서 단어 수 세어정렬하여 출력하기

Page 3: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

• 주어진 소설 어린 왕자의 도입부를 탐색하여 여기에 나오는 단어 수를 세고, 많이 나온 단어 순으로 출력하라. 단어와 단어가 나온 횟수를 class로 만들어 STL 컨테이너인 list에 저장하여 관리한다.

• STL 컨테이너(list)

개념

주요 함수

- push_back() : 리스트 뒤쪽에 추가

- push_front() : 리스트 앞쪽에 추가

- sort() : 내림 차 순으로 정렬

- begin() : 반복자 형으로 시작 위치 반환

- end() : 반복자 형으로 끝 위치 반환

- size() : list가 가지는 크기 반환

list의 반복자

- iterator

- 다음 페이지 예제 참고

Page 4: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

std::list의 사용방법및동작원리

#include <iostream>#include <list>using namespace std;

void main( ){

list<int> lt;

lt.push_back(10); // 리스트 뒤쪽에 추가lt.push_back(20);lt.push_back(30);lt.push_back(40);lt.push_back(50);

list<int>::iterator iter;for( iter = lt.begin() ; iter != lt.end() ; iter++)

cout << *iter << ' ';cout << endl;

lt.push_front(60); // 리스트 앞쪽에 추가lt.push_front(70);

lt.push_front(80);for( iter = lt.begin() ; iter != lt.end() ; iter++)

cout << *iter << ' ';cout << endl;

}

Page 5: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

• void list::sort( void ) 컨테이너에서 재정의 된 “<” 연산자를 통해 정렬

• template <class Compare> void list::sort( Compare comp ) 컨테이너에서 재정의 된 “<“연산자를 사용하지 않고 comp 함수를 별도로 만들어서 정렬하는 것.

comp는 두 개의 컨테이너 파라미터를 받으며 (list의 element와 같은 type) 정렬 비교 기준에참이면 true를 그렇지 않으면 false를 반환하게 작성한다.

std::list의 sort함수 사용방법및동작원리

#include <list>

#include <string>

#include <iostream>

class MyData {

protected:

int m_nId;

std::string m_strName;

public:

bool operator<(const MyData& other) {

if( m_nId < other.m_nId)

return true;

else

return false;

}; // operator< 재정의sort(void)에서 사용됨

// constructor

MyData(int nId, std::string strName)

{

m_nId = nId;

m_strName = strName;

};

MyData(){};

friend bool Comp(MyData first, MyData second)

};

bool Comp(MyData first, MyData second)//비교에 사용되는 함수

{

if( first.m_nId < second.m_nId)

return true;

else

return false;

}

Page 6: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

std::list의 sort함수 사용방법및동작원리

void main()

{

std::list<MyData> dataList;

dataList.push_back( MyData(100, "alones1"));

dataList.push_back( MyData(50, "alones2"));

dataList.push_back( MyData(16, "alones3"));

dataList.push_back( MyData(58, "alones4"));

// 재정의 된 Comp()함수를 사용한 정렬

dataList.sort( Comp );

std::list<MyData>::iterator it = dataList.begin();

// 결과출력id에 따라 오름차순으로 정렬

while( it != dataList.end())

{

std::cout<<"id: "<<(*it).m_nId

<<" name: "<<(*it).m_strName<<std::endl;

++it;

}

}

Page 7: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

제시된소설어린왕자의도입부string theLittlePrince = "\

Once when I was six years old I saw a magnificent picture in a book, called True Stories from Nature,\

about the primeval forest. It was a picture of a boa constrictor in the act of swallowing an animal.\

Here is a copy of the drawing.\n\

In the book it said: \"Boa constrictors swallow their prey whole, without chewing it. After that they\

are not able to move, and they sleep through the six months that they need for digestion.\"\n\

I pondered deeply, then, over the adventures of the jungle. And after some work with a colored pencil\

I succeeded in making my first drawing. My Drawing Number One. It looked like this:\n\

I showed my masterpiece to the grown-ups, and asked them whether the drawing frightened them.\n\

But they answered: \"Frighten? Why should any one be frightened by a hat?\"\n\

My drawing was not a picture of a hat. It was a picture of a boa constrictor digesting an elephant. \

But since the grown-ups were not able to understand it, I made another drawing: I drew the inside of \

the boa constrictor, so that the grown-ups could see it clearly. They always need to have things explained. \

My Drawing Number Two looked like this:\n\

The grown-ups' response, this time, was to advise me to lay aside my drawings of boa constrictors, whether \

from the inside or the outside, and devote myself instead to geography, history, arithmetic and grammar. \

That is why, at the age of six, I gave up what might have been a magnificent career as a painter. \

I had been disheartened by the failure of my Drawing Number One and my Drawing Number Two. Grown-ups never \

understand anything by themselves, and it is tiresome for children to be always and forever explaining \

things to them.\n\

So then I chose another profession, and learned to pilot airplanes. I have flown a little over all parts \

of the world; and it is true that geography has been very useful to me. At a glance I can distinguish \

China from Arizona. If one gets lost in the night, such knowledge is valuable.\n\

In the course of this life I have had a great many encounters with a great many people who have been \

concerned with matters of consequence. I have lived a great deal among grown-ups. I have seen them \

intimately, close at hand. And that hasn't much improved my opinion of them.\n\

Whenever I met one of them who seemed to me at all clear-sighted, I tried the experiment of showing \

him my Drawing Number One, which I have always kept. I would try to find out, so, if this was a person\

of true understanding. But, whoever it was, he, or she, would always say:\n\

\"That is a hat.\"\n\

Then I would never talk to that person about boa constrictors, or primeval forests, or stars. \

I would bring myself down to his level. I would talk to him about bridge, and golf, and politics, \

and neckties. And the grown-up would be greatly pleased to have met such a sensible man.\n\

";

Page 8: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

#include <iostream>#include <iomanip>#include <string> #include <list>using namespace std;

class WordElement {//단어와 나온 수를 관리하는 클래스public:

WordElement();//기본 생성자WordElement(const string& str );//단어를 입력 받는 생성자, nCount=1WordElement(const WordElement& wc);//복사 생성자~WordElement();void print( void );//strWord 와 nCount를 출력

public: //연산자 오버로드WordElement& operator++( void );//나온 횟수를 증가bool operator==( const WordElement& wc );//단어가 같은지 비교bool operator==( const string& word );//단어가 같은지 비교bool operator>( const WordElement& wc );//정렬을 위한 비교, 단어를 비교bool operator<( const WordElement& wc );//정렬을 위한 비교, 단어를 비교bool operator=( const WordElement& wc );//단어를 대입

protected:string strWord;//단어int nCount ;//단어가 나온 횟수//단어가 나온 횟수를 비교하는 연산자를 friend 함수로 등록friend bool CompareCount(const WordElement& first, const WordElement& second);

};

bool CompareCount(const WordElement& first, const WordElement& second)// 단어가 나온 횟수를 비교하는 연산자 구현{/*…*/} //나온 횟수로 비교, 횟수가 같다면, 단어로 비교

Page 9: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

typedef list<WordElement> LIST_WORDCOUNT;//WordElement를 저장하는 list를 정의typedef LIST_WORDCOUNT::iterator LIST_WORDCOUNTIter;//WordElement를 저장하는 list의 iterator를 정의

class WordCount {//단어를 관리하는 클래스public:

WordCount(){};~WordCount(){};

public:void addWord( const string& word ) {

//m_listWC에 word와 같은 단어가 있으면 m_listWC안에 있는 해당 단어의 횟수를 1증가//m_listWC에 word와 같은 단어가 없으면 m_listWC에 신규 단어로 추가

}void sort( void ) {

//std::list 멤버 함수를 사용하여 m_listWC를 정렬}void printSrotByWord( void ){

m_listWC.sort();//단어 순 정렬cout << "Word count = "<< m_listWC.size() << endl;cout << setw(20) << " Word " << setw(5) << " Count "<< endl;cout <<"____________________________" << endl;

//m_listWC의 반복자를 탐색하며 출력}void printSrotByCount( void ){

//나온 횟수 순으로 정렬, 횟수가 같다면, 단어 순 정렬//기본 정보 출력 및 m_listWC의 반복자를 탐색하며 출력

}protected:

LIST_WORDCOUNT m_listWC;};

Page 10: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

void WordCounting (string& source );

int main ( void ) {string theLittlePrince = "\

//..중략";

WordCounting( theLittlePrince );return 0;

}void WordCounting ( const string& source ) {

string::iterator iter = source.begin();string word;WordCount wc;

//iter이 source.end()와 같지 않을 동안 반복{

//iter위치에 'A'~'Z', 'a'~'z'이 외의 값이 있을 경우 iter증가

//word를 초기화//' ', ',', '\n', '.'의 특수 문자가 나타나지 않을 동안 iter의 문자를 word에 추가 대입

//wc에 word를 addWord()함수를 통해 추가}cout << "Print Srot By Word" << endl;wc.printSrotByWord();system( "pause" );cout << endl << "Print Srot By Count" << endl;wc.printSrotByCount();

}

Page 11: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

• 실행 결과

… …

단어로정렬 나온횟수로정렬

Page 12: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

Homework #5

5_2. 예외 클래스 설계 및 구현

<세부 문제에 대해 프로젝트를 각각 만들어서 제출하세요.>

Page 13: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

13

Homework #5

13

#include <iostream>#include <exception>#include <vector>using namespace std;

int main (void) {

vector<int> myvector;myvector.resize(myvector.max_size()+1);

return 0;}

1. length_error 이용

Page 14: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

14

Homework #5

14

#include <exception>#include <string>#include <iostream>using namespace std;

static void f() { throw runtime_error("runtime error called"); }

int main (){

string s ;s.replace(100, 1, 1, 'c');f();return 0;

}

2. runtime_error 이용

Page 15: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

15

Homework #5

15

#include <iostream>#include <stdexcept>#include <bitset>using namespace std;

int main (void) {// bitset 생성자는 0과 1만을 포함하는 문자열을 입력받을 수 있다.

bitset<5> mybitset (string("01234"));return 0;

}

3. invalid_argument

Page 16: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

16

Homework #5

16

#include <string>#include <iostream>

using namespace std;

int main() {string str( "Program" );string rstr( "ming" );str.append( rstr, 5, 3 );cout << str << endl;

}

4. out_of_range

Page 17: Homework #5 - khu.ac.krhaptic.khu.ac.kr/aoop/Homework_5.pdf · 온단어순으로출력하라. 단어와단어가나온횟수를class로만들어STL 컨테이 너인list에저장하여관리한다

17

Homework #5

17

#include <bitset>#include <iostream>

using namespace std;

int main( ){

bitset< 33 > bitset;bitset[32] = 1;bitset[0] = 1;unsigned long x = bitset.to_ulong( );

}

5. overflow_error

typeid( e ).name()에러의 타입을 문자열로 반환