我遇到了麻煩,每當我嘗試編譯這個程序時,我都會在contains函數中得到一個錯誤,它說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;
}
什麼是編譯器錯誤消息? – trojanfoe 2013-03-27 22:19:25
您的代碼還有其他問題。例如,'qs'是'priority_queue',但是你正在向它推送'int'(在'qs.push(i)'行)。 –
2013-03-27 22:24:01