Reputation: 726
I have to define the priority_queue class in the main.
int main(){
...
pri_queue_t<string, vector_t<string>, cmp> q3;
...
}
Therefore, I tried to make a header file like below.
template<typename T, class V, class O> //the last argument is alphabet 'O'
class pri_queue_t{
public:
pri_queue_t(); //constructor
....
}
template<typename T, class V, class O>
pri_queue_t<T, V, O>::pri_queue_t(){} //body of constructor**
The error code is
/home/mys/Desktop/stl_project/2_adp/main.cc: In function ‘int main()’:
/home/mys/Desktop/stl_project/2_adp/main.cc:147:43: error: ‘cmp’ was
not declared in this scope; did you mean ‘bcmp’?
147 | pri_queue_t<string, vector_t<string>, cmp> q3;
| ^~~
| bcmp
/home/mys/Desktop/stl_project/2_adp/main.cc:147:46: error: template
argument 3 is invalid
147 | pri_queue_t<string, vector_t<string>, cmp> q3;
I meant the cmp as option that makes pri-queue ascending. How to make the right constructor? And How to define the cmp?
Upvotes: 0
Views: 47
Reputation: 122133
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
Note the default for the thrid parameter. If you do not know what else to put there then the default is probably fine:
template<typename T, class V>
class pri_queue_t{
public:
pri_queue_t(); //constructor
....
}
template<typename T, class V>
pri_queue_t<T, V>::pri_queue_t(){} //body of constructor**
I am a bit confused by //the last argument is alphabet 'O'
, because the third parameter for priority_queue
is a comparator, not an "alphabet". Anyhow, then in main
:
int main(){
pri_queue_t<string, vector_t<string>> q3;
}
If vector_t
is std::vector
, you could also get rid of the second parameter.
Alternatively you can use the defaults from the priority_queue:
#include <queue>
template <typename T>
struct prio_queue_defaults {
using container_type = typename std::priority_queue<T>::container_type;
using value_compare = typename std::priority_queue<T>::value_compare;
};
template <typename T,
typename container = typename prio_queue_defaults<T>::container_type,
typename compare = typename prio_queue_defaults<T>::value_compare>
struct my_prio_queue {
std::priority_queue<T,container,compare> x;
};
int main() {
my_prio_queue<int> y;
my_prio_queue<int,std::vector<int>> z;
}
Note that there is no need to write a constructor for this simple example, because the compiler generated one already does the right thing.
(The trait prio_queue_defaults
is not really needed here and it also does not help to write less code, I just used it to have meaningful names.)
Upvotes: 3