vs2005 c++ heap使用push_head()异常invalid heap(bug)

阅读更多

最近想使用STL的heap,我的vs2005 Team Edition For Software Developers版本是version 8.0.50727.42,.Net Framework Version 2.0.50727 .

然后看到微软官网的一段使用Heap的代码

  1. //alg_push_heap.cpp
  2. //compilewith:/EHsc
  3. #include
  4. #include
  5. #include
  6. #include
  7. intmain(){
  8. usingnamespacestd;
  9. vector<int>v1,v2;
  10. vector<int>::iteratorIter1,Iter2;
  11. inti;
  12. for(i=1;i<=9;i++)
  13. v1.push_back(i);
  14. random_shuffle(v1.begin(),v1.end());
  15. cout<<"Vectorv1is(";
  16. for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
  17. cout<<*Iter1<<"";
  18. cout<<")."<
  19. //Makev1aheapwithdefaultlessthanordering
  20. make_heap(v1.begin(),v1.end());
  21. cout<<"Theheapedversionofvectorv1is(";
  22. for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
  23. cout<<*Iter1<<"";
  24. cout<<")."<
  25. //Addanelementtotheheap
  26. v1.push_back(10);
  27. cout<<"Theheapv1with10pushedbackis(";
  28. for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
  29. cout<<*Iter1<<"";
  30. cout<<")."<
  31. push_heap(v1.begin(),v1.end());
  32. cout<<"Thereheapedv1with10addedis(";
  33. for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
  34. cout<<*Iter1<<"";
  35. cout<<")."<
  36. //Makev1aheapwithgreaterthanordering
  37. make_heap(v1.begin(),v1.end(),greater<int>());
  38. cout<<"Thegreater-thanheapedversionofv1is\n(";
  39. for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
  40. cout<<*Iter1<<"";
  41. cout<<")."<
  42. v1.push_back(0);
  43. cout<<"Thegreater-thanheapv1with11pushedbackis\n(";
  44. for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
  45. cout<<*Iter1<<"";
  46. cout<<")."<
  47. push_heap(v1.begin(),v1.end(),greater<int>());
  48. cout<<"Thegreaterthanreheapedv1with11addedis\n(";
  49. for(Iter1=v1.begin();Iter1!=v1.end();Iter1++)
  50. cout<<*Iter1<<"";
  51. cout<<")."<
  52. }

发现竟然在push_heap()那里抛了异常。(invalid Heap)

然后无奈去了www.cplusplus.com也下了一段代码:

  1. //rangeheapexample
  2. #include
  3. #include
  4. #include
  5. usingnamespacestd;
  6. intmain(){
  7. intmyints[]={10,20,30,5,15};
  8. vector<int>v(myints,myints+5);
  9. vector<int>::iteratorit;
  10. make_heap(v.begin(),v.end());
  11. cout<<"initialmaxheap:"<
  12. pop_heap(v.begin(),v.end());v.pop_back();
  13. cout<<"maxheapafterpop:"<
  14. v.push_back(99);push_heap(v.begin(),v.end());
  15. cout<<"maxheapafterpush:"<
  16. sort_heap(v.begin(),v.end());
  17. cout<<"finalsortedrange:";
  18. for(unsignedi=0;i""<
  19. cout<
  20. return0;
  21. }

这段代码没有抛异常,运行完好。仔细检查一番,发现可能是vector数组中的元素没有增多的缘故。于是将

pop_heap (v.begin(),v.end()); v.pop_back();改为

pop_heap (v.begin(),v.end()); 这样vector元素就在总数上多了一。

然后运行..相同的错误。

不知道vs2008版本上有没有相同的错误。

你可能感兴趣的:(C,C++,C#,.net)