以下代码继承std :: priority_queue并提供clear()调用内部std::vector的代码clear()
#include<iostream>
#include<queue>
using namespace std;
template<class type>
struct mypq :public priority_queue<type> {
void clear(){
this->c.clear();
}
};
mypq<int>pq;
int main() {
for(int i=0;i<10;++i)
pq.push(i);
pq.clear();
for(int j=-5;j<0;++j)
pq.push(j);
while (!pq.empty()){
cerr<<pq.top()<<endl;
pq.pop();
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用g ++,MSVC++和clang测试它时,它会产生预期的输出:
-1
-2
-3
-4
-5
Run Code Online (Sandbox Code Playgroud)
但我没有看到任何保证,即清除内部向量将pop()与priority_queue不为空时调用相同.虽然我知道其他方法来清除它,比如交换或使用空的priority_queue分配它,但我认为如果这个代码能够很好地工作,那么它会更有效,因为向量中分配的内存是可重用的.所以我想知道这段代码是可移植的还是不会一直有效?
| 归档时间: |
|
| 查看次数: |
569 次 |
| 最近记录: |