gpt4 book ai didi

c++ - 优先队列错误

转载 作者:行者123 更新时间:2023-11-28 03:20:12 25 4
gpt4 key购买 nike

我遇到了麻烦,每当我尝试编译这个程序时,我都会在包含 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;
}

最佳答案

问题是您传递的是 const引用队列,但是 pop()显然不是 const操作,因为它会改变队列。

你应该传递一个非常量引用:

bool contains(priority_queue<T>& q, T val) { .... }

如您所见,您无法在不更改队列的情况下真正检查队列的内容。

下一个错误是您将一个整数插入 std::string 的队列中:

qi.push(i);

你可能是说

qi.push(arr[i]);

注意 ostream& operator<< 的重载对于队列清空队列,所以任何尝试使用 contains将队列打印到 std::cout 之后无论队列的原始内容如何,​​都会产生 false。

查看演示 here .

关于c++ - 优先队列错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15670567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com