我遇到了麻烦,每当我尝试编译这个程序时,我都会在包含 q.pop 的包含函数中得到一个错误。如果该行被注释掉,它将编译得很好,但它仍然给出错误的值。由于某种原因,它总是错误的。
错误是:
priority_queue_demo.cpp: In function 'int main()':
priority_queue_demo.cpp:54:12: error: invalid conversion from 'int' to 'const char*' [-fpermissive]
/usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/basic_string.tcc:214:5: error: initializing argument 1 of 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]' [-fpermissive]
priority_queue_demo.cpp: In function 'bool contains(const std::priority_queue<T>&, T) [with T = int, typename std::vector<T, std::allocator<_Tp1> >::value_type = int]':
priority_queue_demo.cpp:43:47: instantiated from here
priority_queue_demo.cpp:27:3: error: passing 'const std::priority_queue<int>' as 'this' argument of 'void std::priority_queue<_Tp, _Sequence, _Compare>::pop() [with _Tp = int, _Sequence = std::vector<int, std::allocator<int> >, _Compare = std::less<int>]' discards qualifiers [-fpermissive]
#include <iostream>
#include <string>
#include <sstream>
#include <queue>
using namespace std;
template <typename T>
ostream &operator <<(ostream &os, priority_queue<T> &q) {
os << "{";
while (!q.empty()) {
os << q.top() << (!q.empty() ? ", " : "");
q.pop();
}
os << "}";
return os;
}
template <typename T>
bool contains(const priority_queue<T> &q, T val) {
for (int i = 0; i < q.size(); i++) {
if (q.top() == val) return true;
q.pop();
}
return false;
}
int main() {
cout << boolalpha;
priority_queue<int> qi;
for (int i = 0; i < 20; i++)
qi.push(i);
cout << qi << endl;
cout << "qi contians 15: " << contains(qi, 15) << endl;
cout << "qi contians 23: " << contains(qi, 23) << endl;
const int ARR_SIZE = 4;
string arr[ARR_SIZE] = {"cat", "dog", "cow", "elephant"};
cout << endl;
priority_queue<string> qs;
for(int i = 0; i < ARR_SIZE; i++)
qs.push(i);
cout << qs << endl;
while(!qs.empty()) {
qs.pop();
cout << qs << endl;
}
return 0;
}