最近想使用STL的heap,我的vs2005 Team Edition For Software Developers版本是version 8.0.50727.42,.Net Framework Version 2.0.50727 .
然后看到微软官网的一段使用Heap的代码
- //alg_push_heap.cpp
- //compilewith:/EHsc
- #include<vector>
- #include<algorithm>
- #include<functional>
- #include<iostream>
- intmain(){
- usingnamespacestd;
- vector<int>v1,v2;
- vector<int>::iteratorIter1,Iter2;
- inti;
- for(i=1;i<=9;i++)
- v1.push_back(i);
- random_shuffle(v1.begin(),v1.end());
- cout<<"Vectorv1is(";
- for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
- cout<<*Iter1<<"";
- cout<<")."<<endl;
- //Makev1aheapwithdefaultlessthanordering
- make_heap(v1.begin(),v1.end());
- cout<<"Theheapedversionofvectorv1is(";
- for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
- cout<<*Iter1<<"";
- cout<<")."<<endl;
- //Addanelementtotheheap
- v1.push_back(10);
- cout<<"Theheapv1with10pushedbackis(";
- for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
- cout<<*Iter1<<"";
- cout<<")."<<endl;
- push_heap(v1.begin(),v1.end());
- cout<<"Thereheapedv1with10addedis(";
- for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
- cout<<*Iter1<<"";
- cout<<")."<<endl<<endl;
- //Makev1aheapwithgreaterthanordering
- make_heap(v1.begin(),v1.end(),greater<int>());
- cout<<"Thegreater-thanheapedversionofv1is\n(";
- for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
- cout<<*Iter1<<"";
- cout<<")."<<endl;
- v1.push_back(0);
- cout<<"Thegreater-thanheapv1with11pushedbackis\n(";
- for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
- cout<<*Iter1<<"";
- cout<<")."<<endl;
- push_heap(v1.begin(),v1.end(),greater<int>());
- cout<<"Thegreaterthanreheapedv1with11addedis\n(";
- for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
- cout<<*Iter1<<"";
- cout<<")."<<endl;
- }
发现竟然在push_heap()那里抛了异常。(invalid Heap)
然后无奈去了www.cplusplus.com也下了一段代码:
- //rangeheapexample
- #include<iostream>
- #include<algorithm>
- #include<vector>
- usingnamespacestd;
- intmain(){
- intmyints[]={10,20,30,5,15};
- vector<int>v(myints,myints+5);
- vector<int>::iteratorit;
- make_heap(v.begin(),v.end());
- cout<<"initialmaxheap:"<<v.front()<<endl;
- pop_heap(v.begin(),v.end());v.pop_back();
- cout<<"maxheapafterpop:"<<v.front()<<endl;
- v.push_back(99);push_heap(v.begin(),v.end());
- cout<<"maxheapafterpush:"<<v.front()<<endl;
- sort_heap(v.begin(),v.end());
- cout<<"finalsortedrange:";
- for(unsignedi=0;i<v.size();i++)cout<<""<<v[i];
- cout<<endl;
- return0;
- }
这段代码没有抛异常,运行完好。仔细检查一番,发现可能是vector数组中的元素没有增多的缘故。于是将
pop_heap (v.begin(),v.end()); v.pop_back();改为
pop_heap (v.begin(),v.end()); 这样vector元素就在总数上多了一。
然后运行..相同的错误。
不知道vs2008版本上有没有相同的错误。