функция с парой <elem> в c ++

0

Я пишу проект создания maxheap с идентификатором объекта и приоритетом. Приоритет - это int для сравнения. Идентификатор объекта может быть либо int, char, либо string.

Я создал функцию сравнения, которая необходима в куче.

class pairpairCompare {
public:
  static bool lt(pair<int,int> x, pair<int,int> y) { return x.second < y.second; }
  static bool eq(pair<int,int> x, pair<int,int> y) { return x.second == y.second; }
  static bool gt(pair<int,int> x, pair<int,int> y) { return x.second > y.second; }
};

И он отлично работает для pair<int, int>* pairArr=new pair<int, int>[maxArrayRoom];

позвонив

maxheap<pair<int, int>,pairpairCompare> PairTtest(pairArr,0,maxArrayRoom);

Теперь я хочу обновить так, что pair<char, int>* pairArr=new pair<int, int>[maxArrayRoom]; или pair<string, int>* pairArr=new pair<int, int>[maxArrayRoom]; может работать

Я попробовал это.

template <class Elem>
class pairpairCompare {
public:
  static bool lt(pair<Elem,int> x, pair<Elem,int> y) { return x.second < y.second; }
  static bool eq(pair<Elem,int> x, pair<Elem,int> y) { return x.second == y.second; }
  static bool gt(pair<Elem,int> x, pair<Elem,int> y) { return x.second > y.second; }
};

Он возвращает ошибку. Я также пробовал это. Все еще ошибка.

pair<template <class Elem>, int>
class pairpairCompare {
public:
  static bool lt(pair<Elem,int> x, pair<Elem,int> y) { return x.second < y.second; }
  static bool eq(pair<Elem,int> x, pair<Elem,int> y) { return x.second == y.second; }
  static bool gt(pair<Elem,int> x, pair<Elem,int> y) { return x.second > y.second; }
};

Я знаю, что это простой вопрос. Но я исхожу из С# background и имею проблемы с поиском правильного синтаксиса для работы вышеприведенной функции, чтобы я мог вызвать эту функцию в этом.

maxheap<pair<char, int>,pairpairCompare> PairTtest(pairArr,0,maxArrayRoom); или maxheap<pair<string, int>,pairpairCompare> PairTtest(pairArr,0,maxArrayRoom);

heap.h

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
// Max-heap class
template <class Elem, class Comp> class maxheap {
private:
  Elem* Heap;          // Pointer to the heap array
  int size;            // Maximum size of the heap
  int n;               // Number of elements now in the heap
  void siftdown(int);  // Put element in its correct place
public:
  maxheap(Elem* h, int num, int max)     // Constructor
    { Heap = h;  n = num;  size = max;  buildHeap(); }
  int heapsize() const       // Return current heap size
    { return n; }

  bool isLeaf(int pos) const // TRUE if pos is a leaf
    { return (pos >= n/2) && (pos < n); }
  int leftchild(int pos) const
    { return 2*pos + 1; }    // Return leftchild position
  int rightchild(int pos) const
    { return 2*pos + 2; }    // Return rightchild position
  int parent(int pos) const  // Return parent position
    { return (pos-1)/2; }
  bool insert(const Elem&);  // Insert value into heap
  bool removemax(Elem&);     // Remove maximum value
  bool remove(int, Elem&);   // Remove from given position
  void buildHeap()           // Heapify contents of Heap
    { for (int i=n/2-1; i>=0; i--) siftdown(i); }

  bool enqueue(int ObjID, int priority) 
    // inserting new element. Need the objid, priority, and reference to existing heap
{
    pair<int,int> newPair=make_pair(ObjID,priority);//creating new pair
    return insert(newPair);//calling maxheap->insert function. return success / failed. 
}

bool dequeue()
    //removing the highest priority. (priority)
{
    pair<int,int> removedPair;//create pair to received removed value
    if(removemax(removedPair))// call maxheap->remove max for removed pair
    {
        cout<<"Object ID of max priority: "<<removedPair.first<<endl;//show the removed object ID
        return true;
    }
    else
    {
        cout<<"Nothing to remove"<<endl;
        return false;
    }

}

bool changeweight(int ObjID, int newPriority)
    //changing the priority number of object ID
{
    bool returnBool=false;//set return variable success or fail

    for(int a=0;a<heapsize();a++)//sequential search to find object ID
    {
        if(pairArr[a].first==ObjID)//check whether object ID is the same
        {
            pairArr[a].second=newPriority;//update priority value
            returnBool=true;//update return variable
            break;//break array
        }
    }
    if(returnBool)//if object ID is found
    {
        buildHeap();//need to rebuild the heap coz priority variable is changed.
    }
    return returnBool;//return success or fail

}


};

template <class Elem, class Comp> // Utility function
void maxheap<Elem, Comp>::siftdown(int pos) {
  while (!isLeaf(pos)) {     // Stop if pos is a leaf
    int j = leftchild(pos);  int rc = rightchild(pos);
    if ((rc < n) && Comp::lt(Heap[j], Heap[rc]))
      j = rc;        // Set j to greater child value
    if (!Comp::lt(Heap[pos], Heap[j])) return; // Done
    swap(Heap, pos, j);
    pos = j;         // Move down
  }
}

template <class Elem, class Comp> // Insert element
bool maxheap<Elem, Comp>::insert(const Elem& val) {
  if (n >= size) return false; // Heap is full
  int curr = n++;
  Heap[curr] = val;            // Start at end of heap
  // Now sift up until curr parent > curr
  while ((curr!=0) &&
         (Comp::gt(Heap[curr], Heap[parent(curr)]))) {
    swap(Heap, curr, parent(curr));
    curr = parent(curr);
  }
  return true;
}

template <class Elem, class Comp> // Remove max value
bool maxheap<Elem, Comp>::removemax(Elem& it) {
  if (n == 0) return false; // Heap is empty
  swap(Heap, 0, --n);       // Swap max with last value
  if (n != 0) siftdown(0);  // Siftdown new root val
  it = Heap[n];             // Return deleted value
  return true;
}

// Remove value at specified position
template <class Elem, class Comp>
bool maxheap<Elem, Comp>::remove(int pos, Elem& it) {
  if ((pos < 0) || (pos >= n)) return false; // Bad pos
  swap(Heap, pos, --n);           // Swap with last value
  while ((pos != 0) &&
         (Comp::gt(Heap[pos], Heap[parent(pos)])))
    swap(Heap, pos, parent(pos)); // Push up if large key
  siftdown(pos);      // Push down if small key
  it = Heap[n];
  return true;
}
/*
class pairpairCompare {
public:
  static bool lt(pair<int,int> x, pair<int,int> y) { return x.second < y.second; }
  static bool eq(pair<int,int> x, pair<int,int> y) { return x.second == y.second; }
  static bool gt(pair<int,int> x, pair<int,int> y) { return x.second > y.second; }
};
*/

template<class Elem>
class pairpairCompare {
public:
  static bool lt(pair<Elem,int> x, pair<Elem,int> y) { return x.second < y.second; }
  static bool eq(pair<Elem,int> x, pair<Elem,int> y) { return x.second == y.second; }
  static bool gt(pair<Elem,int> x, pair<Elem,int> y) { return x.second > y.second; }
};

template<class Elem>
inline void swap(Elem A[], int i, int j) {
  Elem temp = A[i];
  A[i] = A[j];
  A[j] = temp;
}

Heap_Implement.cpp

#include "Heap.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

const int maxArrayRoom=20;// maximum array room. global variable. 
pair<int, int>* pairArr=new pair<int, int>[maxArrayRoom];// creating a pair array with 2 integers

template <class Elem>
//choice 0 => negative values 1 => zero and negative values, 2 => same type is fine
void GetInputValue(Elem& elemInput,int choice)// checking input values for correct types and range
{
    if(choice==0)//correct type and greater than 0 // use for integers
    {
        while (!(cin >> elemInput) || (elemInput<0) )
        {
            cin.clear(); //clear bad input flag
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
            cout << "Invalid input; please re-enter."<<endl;
        }
    }
    if(choice==1)//correct type and greater than 1// use for integers
    {
        while (!(cin >> elemInput) || (elemInput<=0) )
        {
            cin.clear(); //clear bad input flag
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
            cout << "Invalid input; please re-enter."<<endl;
        }
    }
    else if(choice==2)
    {
            while (!(cin >> elemInput))//correct type only. use for all types integers, double, char
        {
            cin.clear(); //clear bad input flag
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
            cout << "Invalid input; please re-enter."<<endl;
        }
    }
}
int main()
{
    maxheap<pair<int, int>,pairpairCompare> PairTtest(pairArr,0,maxArrayRoom);//create heap with empty array
        cout<<"Press=> 1 to add. 2 to remove. 3 to change. 4 to see all array. 0 to quit"<<endl;//menus

    while(1)//infinite loop
    {   
        int inputInt=-1;//create input variable
        GetInputValue(inputInt,0);//get input
        if(inputInt==1)//adding new priority
        {
            int ObjID, priority=-1;
            cout<<"Key in Object ID"<<endl;//ask for object id
            GetInputValue(ObjID,2);
            cout<<"Key in priority"<<endl;//ask for priority id
            GetInputValue(priority,2);
            if(PairTtest.enqueue(ObjID,priority))//call enqueue to add. if succeeeded
            {
                cout<<"Succeeded"<<endl;
            }
            else//failed. may b array full / sth else
            {
                cout<<"Failed"<<endl;
            }           
        }
        else if(inputInt==2)//removing the max priority obj
        {
            PairTtest.dequeue();
        }
        else if(inputInt==3)//change the priority
        {
            int ObjID, priority=-1;
            cout<<"Key in Object ID"<<endl;//ask for object id
            GetInputValue(ObjID,2);
            cout<<"Key in priority"<<endl;//ask for priority
            GetInputValue(priority,2);
            if(PairTtest.changeweight(ObjID,priority))//call changeweight
            {
                cout<<"Succeeded"<<endl;//success
            }
            else
            {
                cout<<"Failed"<<endl;//failure. may b object is not in array

            }
        }
        else if(inputInt==4)//show heap array
        {
            cout<<"current size: "<<PairTtest.heapsize()<<endl;//show current size
            cout<<"-> Object ID & Priority"<<endl;
            for(int a=0;a<PairTtest.heapsize();a++)//loop to show all array
            {
                cout<<"-> "<< pairArr[a].first<< " & "<< pairArr[a].second<<endl;
            }
            cout<<"END of max heap"<<endl;
        }
        else if(inputInt==0)//quit
        {
            cout<<"BYE"<<endl;
            break;//quit loop
        }
        else//invalid input
        {
            cout << "Invalid input; please re-enter."<<endl;
        }

    }
    return 1;
}
  • 1
    И что за ошибка?
  • 0
    Я знаю, что должен был опубликовать ошибку. Однако я не могу запустить программу прямо сейчас. Я буду публиковать это в 4,5 часа. Приносим извинения за неудобства.
Показать ещё 4 комментария
Теги:

1 ответ

0

Ну, код, который вы опубликовали, дает мне ошибку:

cannot convert 'std::pair<int, int>*' to 'std::pair<char, int>*'

Ваше первое намерение - это нормально, все, что вам нужно изменить:

pair<char, int>* pairArr=new pair<int, int>[maxArrayRoom];
pair<string, int>* pairArr=new pair<int, int>[maxArrayRoom];

от

pair<char, int>* pairArr=new pair<char, int>[maxArrayRoom];      // note "new pair<char ...
pair<string, int>* pairArr=new pair<string, int>[maxArrayRoom];  // note "new pair<string ...

Также вам нужно создать экземпляр функции pairpairCompare, чтобы использовать его, так как теперь это шаблон:

maxheap<pair<char, int>, pairpairCompare<char, int> > PairTtest(pairArr,0,maxArrayRoom);
maxheap<pair<string, int>,pairpairCompare<string, int> > PairTtest(pairArr,0,maxArrayRoom);

и, конечно, как было предложено Jarod42, вы можете использовать векторы.

std::vector<std::pair<char, int> > pairArr(maxArrayRoom);

Ошибка, которая дает вам код, по-прежнему необходима, это может быть нечто, что не покрывает этот ответ. Я отвечаю на это, используя информацию, которую мы можем видеть в вашем вопросе.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню