2012-04-20 4 views
3

제목, 장르, 연도, 등급, 주연 배우 등 400 개 이상의 영화 (연결된 목록을 사용하여 함께 연결됨)를 검색하는 프로그램을 만드는 작업이 있습니다.연결된 목록 검색, 다양한 데이터 유형

catch가 있지만 링크 된 목록을 통해 검색을 수행 할 수있는 검색 기능은 하나만 허용됩니다. 또한, 해당 검색 기능에서, 우리는 분명히

while (moviePtr != NULL) 

이 경우 배우 검색 여러 인스턴스 자신의 것입니다 ... 같은 것입니다 내 경우에 가정 루프하는 동안 하나를 허용하거나 전용 장르 검색. 배우, 장르, 평점, 연도, 하위 장르 및 지원 배우의 경우, 발견 된 모든 인스턴스를 출력해야합니다. (예를 들어, Kevin Bacon이 x-men과 노트북에 있다면, 그 중 하나가 아니라 출력 파일에 출력해야합니다).

나는 우리가 주어진 이러한 제한 사항으로 인해 완전히 혼란 스러움을 발견했습니다. 검색 기능이 다른 데이터 유형을 어떻게 처리합니까? (연도와 등급은 정수로 선언되어야 함). 정확히 내가 무엇을 찾고 있는지 어떻게 알 수 있을까요? 배우를 찾고 있다면 제목 검색도 원하지 않습니다.

시작 및 시작 방법에 대한 제안은 매우 감사하겠습니다.

편집 : 안녕하세요 모든 생각 이드 무슨 짓을했는지 너희들을 업데이 트하십시오. 세 가지 검색 기능이 있습니다. 하나는 숫자 값 (연도와 등급)이고, 1은 장르와 배우, 마지막으로 제목은 1입니다.

다음은이 세 가지 코드입니다. 우선 표제 seach.

void TitleSearched(MovieNode*head, 
       string titleSearched, 
       ofstream& outFile) 
{ 
MovieNode* moviePtr; 
bool found; 

moviePtr = head; 
found = false; 

while (moviePtr !=NULL & !found) 
{ 
    if (moviePtr-> title == titleSearched) 
    { 
     found = true; 
    } 
    else 
    { 
     moviePtr = moviePtr -> next; 
    } 

} 
if (found) 
{ 
    cout << endl << titleSearched << " has been found!\n"; 
    TitleOutput (moviePtr,outFile); 
} 
else 
{ 
    cout << endl << titleSearched << " was not found.\n"; 
} 
} 

이제 연/등급 검색.

마지막으로 장르/배우 검색.

int ItemSearch (MovieNode* head,string itemSearched, ofstream& outFile) 
{ 
int instances; 
MovieNode* moviePtr; 


moviePtr = head; 
instances = 0; 






    while (moviePtr !=NULL) 
    { 
     if (moviePtr-> genre == itemSearched || moviePtr ->subGenre == itemSearched) 
     { 

      instances = instances +1; 
      OutList(moviePtr,outFile,"Genre",itemSearched,instances); 
      moviePtr = moviePtr -> next; 
     } 
     else if (moviePtr->leadActor == itemSearched || moviePtr->supportActor == itemSearched) 
     { 

      instances = instances +1; 
      OutList(moviePtr,outFile,"Actor",itemSearched,instances); 
      moviePtr = moviePtr -> next; 
     } 
     else 
     { 
      moviePtr = moviePtr ->next; 
     } 


    } 



    return instances; 
} 

내 작업이 무엇인지 상기시켜 드리고 싶습니다. (결합 될 때 빈 공간 기능을 것입니다하지만, ID가이 가정) 1.

하나만 검색 할 때 루프가 주어진 기능에 3. 하나 개의 반환하면서 하나 2.have에이 세 가지 검색 기능을 결합 내 주요 문제는 내가 beileve 내 int 및 문자열입니다. 등급 또는 연도를 문자열로 선언 할 수 없습니다. 그리고 세 가지 모두를 빗질하는 코드의 형식이 나에게 큰 고통을주고 있습니다.

+0

검색 기준은 찾고있는 것을 지정합니다. 즉"Kevin Bacon"+ "배우"또는 그들이 무엇을 찾고 있는지 추측해야합니까? – Kiril

+0

사용자는 열거 형을 사용하여 메뉴에서 검색 할 항목을 선택합니다. 예를 들어, 0을 입력하고 종료합니다. 1 - 제목 검색, 2 - 검색 내 순위, 3 - 연도 별 검색, 4 - 배우 검색, etc. –

+0

새 편집을 추가했습니다. 고마워요! –

답변

2

술어를 매개 변수로 허용하는 방식으로 검색 기능을 작성할 수 있습니다. 술어 (predicate)는 일종의 "functionoid"입니다. 즉, 함수처럼 "호출"될 수있는 기능을 말합니다. 함수이거나 람다 또는 함수 객체 일 수 있습니다.)

C++ 표준 라이브러리의

, 술어는 다음과 같이) 당신이 코드를 볼 수 있다는 일반적인 그래서 (표준 컨테이너를 사용하여 표준 알고리즘의 많은 사용됩니다

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 
#include <cctype> 

bool begins_with_s(std::string s) 
{ 
    return s.length() > 0     && 
      std::toupper(s.at(0)) == 'S'; 
} 

bool contains_a_number(std::string s) 
{ 
    return std::find_if(s.begin(), s.end(), std::isdigit) != s.end(); 
} 

int main() 
{ 
    std::string movies_array[] = 
    { 
     "King Kong", 
     "Singin in the Rain", 
     "Die Hard 2", 
     "Superman", 
     "Star Wars", 
     "Jaws 3" 
    }; 
    std::vector<std::string> movies(std::begin(movies_array), 
            std::end(movies_array)); 

    // Use predicate - count if the movie name begins with "S" 
    std::cout << "Movies beginning with S: " 
     << std::count_if(movies.begin(), movies.end(), begins_with_s) 
     << std::endl; 

    // Use predicate - count if the movie name contains a number 
    std::cout << "Movies containing a number: " 
     << std::count_if(movies.begin(), movies.end(), contains_a_number) 
     << std::endl; 
} 

방법이 C++ 표준 함수에 함수를 전달 (A와 같은 기능을 치료 - 알고리즘은 그것은 생각의 기능 프로그래밍 학교에서 기술의

template< typename PredicateType > 
void my_function(PredicateType predicate) 
{ 
    Movie my_movie; 
    predicate(my_movie); 
} 

의 라인을 따라, 술어를 나타내는 템플릿 인수를 받아들이는 이런 식으로되어 구현 "첫 번째 cla ss citizen ").

2

검색 기능에 매개 변수로 "일치"기능을 부여하고 모든 영화에서이 일치 기능을 호출하여 영화가 일치하는지 확인할 수 있습니다. 그런 다음 다른 일치 함수로 검색 함수를 호출 할 수 있습니다. 이 같은

뭔가 :

bool matches_actor(movie& m, const std::string& actor) 
{ 
    return m.actor == actor; 
} 

과 같은 특정 쿼리를 호출 :

template <typename MatchFunction> 
void search_movies(movie* moviePtr, MatchFunction match) 
{ 
    while (moviePtr != NULL) 
    { 
     if (match(*moviePtr)) 
     { 
      // output movie 
     } 
     moviePtr = moviePtr->next; 
    } 
} 

당신은 다음과 같이 일치하는 함수를 선언 할 수

search_movies(moviePtr, std::bind(matches_actor, _1, "Morgan Freeman")); 

(std::bind입니다 <functional>의 C++ 11 함수이며, 동등하게 0123을 사용할 수 있습니다.또는 std::bind2nd)

다른 방법으로 당신이 일을 더 C 스타일의 방식을 선호하는 경우, 당신은 같은 것을 할 수있는 : 거기에, 경기를 확인하기 위해 펑터를 전달하는 옵션 외에

void search_movies(movie* moviePtr, bool (*match)(movie*, void*), void* match_arg) 
{ 
    while (moviePtr != NULL) 
    { 
     if (match(moviePtr, match_arg)) 
     { 
      // output movie 
     } 
     moviePtr = moviePtr->next; 
    } 
} 
... 
bool matches_actor(movie* m, void* actor) 
{ 
    return m.actor == *((std::string*)actor); 
} 
... 
std::string actor = "Morgan Freeman"; 
search_movies(moviePtr, &matches_actor, (void*)(&actor)); 
+0

죄송합니다. 우리는이 웹 사이트를 포함하여 우리의 모든 기능에서 단 하나의 수익만을 허용 한 것을 언급하는 것을 잊어 버렸습니다. –

+0

@RileyFrancona : 복수 수익은 어디에서 볼 수 있습니까? – HighCommander4

2

을 다른 옵션이 있습니다. 하나는 이러한 옵션은 (당신이 boost::optional 또는 손수 접근 또는 사용 포인터를 사용할 수 있습니다 확인하기 위해 선택하는 일련의 조건을 복용 할 것 예를 들면 다음과 같습니다.

void print_matching(node* list, int * year, std::string * actor...) { 
    // iterate over the list: 
    while (...) { 
     if ( (!year || ptr->year == *year) 
     && (!actor || ptr->actor == *actor) 
     && ... 
     ) 
     { 
      // Film matches, print it 
     } 
    } 
} 

함수 서명을 단순화하기 위해 당신이 캡슐화하는 search_pattern 유형을 만들 수 있습니다 테스트 할 필드 기능을

이 지난 경우
struct pattern { 
    bool check_actor; 
    std::string actor; 
    bool check_year; 
    int year; 
}; 

void print_matching(node* list, pattern const & p) { 
    // iterate over the list: 
    while (...) { 
     if ( (!p.check_year || ptr->year == p.year) 
     && (!p.check_actor || ptr->actor == p.actor) 
     && ... 
     ) 
     { 
      // Film matches, print it 
     } 
    } 
} 

, 실제로 pattern 객체로 테스트를 이동할 수 있으며,이 : (다른 접근 방법을 사용하여 예 : bools은 선택성을 결정하는)

부울 패턴 :: 일치 (영화 cosnt & m) const { return (! check_year || m.year == year) & & (! check_actor || m.actor == actor); } 공극 print_matching (* 노드리스트 패턴 CONST & P)리스트 위에 {// 대하여 반복 : 동안 (...) { 경우 (p.matches (목록 -> 데이터)) {// 필름 일치, 인쇄 } } }

+0

안녕 모두, 나는 내가 무엇을하기로 결정했는지에 관해 당신에게 알려줄 것이라고 생각했습니다. Im은 검색 기능을 제목, 연도 및 평가에 각각 하나씩, 장르와 배우에 대해 세 가지 기능으로 나눴습니다. 각각에 대한 코드를 작성합니다. –