我想實現一個優先級隊列,它使用一個具有用於定義隊列中對象的優先級的const成員的對象。以下是我使用的是什麼具有const成員的對象的優先級隊列比較器
#include <vector>
#include <queue>
class Event {
public:
Event(float _time) : time(_time) {};
const float time;
};
struct EventComp {
public:
bool operator()(const Event& a, const Event& b) const {
return a.time < b.time;
}
};
class EventQueue {
private:
std::priority_queue<Event, std::vector<Event>, EventComp> events;
};
int main(int argc, char *argv[])
{
EventQueue q;
}
當我嘗試編譯的精簡版(使用G ++ -std = C++ 11),我收到以下錯誤消息,我不太理解。
g++ -std=c++11 events.cpp -o events
In file included from /usr/include/c++/4.8/queue:62:0,
from events.cpp:2:
/usr/include/c++/4.8/bits/stl_heap.h: In instantiation of ‘void std::__adjust_heap(_RandomAccessIterator, _Distance, _Distance, _Tp, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Event*, std::vector<Event> >; _Distance = long int; _Tp = Event; _Compare = EventComp]’:
/usr/include/c++/4.8/bits/stl_heap.h:448:15: required from ‘void std::make_heap(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Event*, std::vector<Event> >; _Compare = EventComp]’
/usr/include/c++/4.8/bits/stl_queue.h:411:48: required from ‘std::priority_queue<_Tp, _Sequence, _Compare>::priority_queue(const _Compare&, _Sequence&&) [with _Tp = Event; _Sequence = std::vector<Event>; _Compare = EventComp]’
events.cpp:15:7: required from here
/usr/include/c++/4.8/bits/stl_heap.h:315:29: error: use of deleted function ‘Event& Event::operator=(Event&&)’
*(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + __secondChild));
^
events.cpp:4:7: note: ‘Event& Event::operator=(Event&&)’ is implicitly deleted because the default definition would be ill-formed:
class Event {
^
events.cpp:4:7: error: non-static const member ‘const float Event::time’, can’t use default assignment operator
In file included from /usr/include/c++/4.8/queue:62:0,
from events.cpp:2:
/usr/include/c++/4.8/bits/stl_heap.h:321:29: error: use of deleted function ‘Event& Event::operator=(Event&&)’
*(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first
^
我假定priority_queue
的內部結構的一些部分需要移動賦值運算符插入元素,但const
構件似乎防止操作者被定義。我試着用五條規則,但似乎沒有解決。我需要添加到類定義才能使其工作?
編輯:我知道,我可以從成員變量去除const
預選賽中,使其private
,並添加一個訪問成員函數來獲取變量的值,但我寧願把它public
和const
,所以我對保持成員變量的解決方案很感興趣(如果甚至可以的話)。
FWIW其上[_'clang'_]作品(http://rextester.com/CULSS5171) – P0W 2014-12-27 18:31:45
來縮小問題看是否'矢量'編譯 –
bolov
2014-12-27 18:32:54
一些'VECTOR'的和'priority_queue'操作需要'MoveAssignable'。在你使用'const'數據成員的情況下,幾乎沒有辦法給它明智的賦值語義。使'time'非常量,如果你想避免修改,請將其設爲private,並提供一個getter。 – 2014-12-27 18:36:59