사용자 지정 형식으로 STL PRIORITY_QUEUE 클래스 사용

이 문서에서는 사용자 지정(사용자 정의) 데이터 형식을 사용하는 STL(표준 템플릿 라이브러리) priority_queue 템플릿 컨테이너 어댑터 클래스를 정의하는 방법을 설명합니다.

원래 제품 버전: Visual C++
원본 KB 번호: 837697

요약

이 문서에서는 구조 및 클래스와 같은 사용자 지정(사용자 정의) 데이터 형식과 함께 STL priority_queue 템플릿 컨테이너 어댑터 클래스를 사용하는 방법을 설명합니다. 이 문서에서는 왼쪽 꺾쇠 괄호() 또는 오른쪽 꺾쇠 괄호>(<) 비교 연산자를 오버로드하여 클래스 멤버의 순서를 지정 priority_queue 하는 방법도 설명합니다. 이 문서에서는 사용자 지정(사용자 정의) 데이터 멤버를 포함하는 컨테이너 클래스 변수를 선언 priority_queue 하는 방법과 프로그램에서 이러한 변수에 액세스하는 방법에 대해서도 설명합니다. 이 문서의 정보는 관리되지 않는 Visual C++ 코드에만 적용됩니다.

요구 사항

이 문서에서는 STL 데이터 형식 및 컨테이너 형식을 사용하는 프로그래밍에 익숙하다고 가정합니다.

사용자 지정 데이터 형식 만들기

클래스는 priority_queue 일부 기본 컨테이너 형식의 최상위 요소에 대한 액세스를 제한하는 템플릿 컨테이너 어댑터 클래스입니다. 기본 컨테이너 형식의 최상위 요소에 대한 액세스를 제한하는 것이 항상 가장 높은 우선 순위입니다. 클래스에 priority_queue 새 요소를 추가할 수 있으며 클래스의 priority_queue 최상위 요소를 검사하거나 제거할 수 있습니다.

사용자 지정(사용자 정의) 데이터 형식과 함께 클래스를 사용 priority_queue 하려면 다음 코드와 같이 사용자 지정 데이터 형식을 정의해야 합니다.

//Define a custom data type.
class Student
{
    public:
    char* chName;
    int nAge;
    Student(): chName(""),nAge(0){}
    Student( char* chNewName, int nNewAge ):chName(chNewName), nAge(nNewAge){}
};

참고

동일한 용도로 구조를 정의하려면 이 코드 샘플에서 을 로 struct 바꿀 class 수 있습니다.

QUEUE 순서 지정

다음 코드 샘플과 같이 오른쪽 꺾쇠 괄호 또는 왼쪽 꺾쇠 괄호 비교 연산자를 오버로드하여 클래스 멤버의 priority_queue 순서를 지정할 수 있습니다.

//Overload the < operator.
bool operator< (const Student& structstudent1, const Student &structstudent2)
{
    return structstudent1.nAge > structstudent2.nAge;
}
//Overload the > operator.
bool operator> (const Student& structstudent1, const Student &structstudent2)
{
    return structstudent1.nAge < structstudent2.nAge;
}

사용자 지정 데이터 형식을 사용하여 priority_queue 변수 만들기 및 액세스

템플릿 클래스의 priority_queue 프로토타입은 다음과 같습니다.

template <
  class Type,
  class Container=vector<Type>,
  class Compare=less<typename Container::value_type>
>
class priority_queue

priority_queue 다음과 같이 사용자 지정 데이터 형식 및 비교 연산자를 지정하는 변수를 선언합니다.

priority_queue<Student, vector<Student>,less<vector<Student>::value_type> > pqStudent1;

다음과 같이 , , popempty기타 메서드와 같은 push클래스의 priority_queue 다른 메서드를 사용할 수 있습니다.

// Add container elements.
pqStudent1.push( Student( "Mark", 38 ));
pqStudent1.push( Student( "Marc", 25 ));
pqStudent1.push( Student( "Bill", 47 ));
pqStudent1.push( Student( "Andy", 13 ));
pqStudent1.push( Student( "Newt", 44 ));

//Display container elements.
while ( !pqStudent1.empty())
{
    cout << pqStudent1.top().chName << endl;
    pqStudent1.pop();
}

전체 코드 목록

// The debugger cannot handle symbols that are longer than 255 characters.
// STL frequently creates symbols that are longer than 255 characters.
// When symbols are longer than 255 characters, the warning is disabled.
#pragma warning(disable:4786)
#include "stdafx.h"
#include <queue>

#using <mscorlib.dll>

#if _MSC_VER > 1020 // if VC++ version is > 4.2
  using namespace std; // std c++ libs implemented in std
#endif
using namespace System;

//Define a custom data type.
class Student
{
    public:
    char* chName;
    int nAge;
    Student(): chName(""),nAge(0){}
    Student( char* chNewName, int nNewAge ):chName(chNewName), nAge(nNewAge){}
    };

    //Overload the < operator.
    bool operator< (const Student& structstudent1, const Student &structstudent2)
    {
        return structstudent1.nAge > structstudent2.nAge;
    }
    //Overload the > operator.
    bool operator> (const Student& structstudent1, const Student &structstudent2)
    {
        return structstudent1.nAge < structstudent2.nAge;
    }

    int _tmain()
    {
      //Declare a priority_queue and specify the ORDER as <
      //The priorities will be assigned in the Ascending Order of Age
      priority_queue<Student, vector<Student>,less<vector<Student>::value_type> > pqStudent1;

      //declare a priority_queue and specify the ORDER as >
      //The priorities will be assigned in the Descending Order of Age
      priority_queue<Student, vector<Student>,greater<vector<Student>::value_type> > pqStudent2;

      // Add container elements.
      pqStudent1.push( Student( "Mark", 38 ));
      pqStudent1.push( Student( "Marc", 25 ));
      pqStudent1.push( Student( "Bill", 47 ));
      pqStudent1.push( Student( "Andy", 13 ));
      pqStudent1.push( Student( "Newt", 44 ));

      //Display container elements.
      while ( !pqStudent1.empty())
      {
          cout << pqStudent1.top().chName << endl;
          pqStudent1.pop();
      }
      cout << endl;

      // Add container elements.
      pqStudent2.push( Student( "Mark", 38 ));
      pqStudent2.push( Student( "Marc", 25 ));
      pqStudent2.push( Student( "Bill", 47 ));
      pqStudent2.push( Student( "Andy", 13 ));
      pqStudent2.push( Student( "Newt", 44 ));

      //Display container elements.
      while ( !pqStudent2.empty())
      {
          cout << pqStudent2.top().chName << endl;
          pqStudent2.pop();
      }
      cout << endl;
      return 0;
    }
}

이전 코드 샘플을 성공적으로 컴파일하려면 Visual C++에서 공용 언어 런타임 지원 컴파일러 옵션(/clr:oldSyntax)을 추가해야 합니다. Visual C++에서 공용 언어 런타임 지원 컴파일러 옵션을 추가하려면 다음 단계를 수행합니다.

  1. 프로젝트를 클릭한 다음 ProjectName> 속성을 클릭합니다<.

    참고

    <ProjectName> 은 프로젝트 이름의 자리 표시자입니다.

  2. 구성 속성을 확장한 다음 일반을 선택합니다.

  3. 오른쪽 창의 공용 언어 런타임 지원 프로젝트 설정에서 공용 언어 런타임 지원, 이전 구문(/clr:oldSyntax)을 선택하고 적용을 선택한 다음 확인을 선택합니다.

공용 언어 런타임 지원 컴파일러 옵션에 대한 자세한 내용은 /clr(공용 언어 런타임 컴파일)을 참조하세요.