最近想使用STL的heap,我的vs2005 Team Edition For Software Developers版本是version 8.0.50727.42,.Net Framework Version 2.0.50727 .
然后看到微软官网的一段使用Heap的代码
- // alg_push_heap.cpp
- // compile with: /EHsc
- #include <vector>
- #include <algorithm>
- #include <functional>
- #include <iostream>
- int main( ) {
- using namespace std;
- vector <int> v1, v2;
- vector <int>::iterator Iter1, Iter2;
- int i;
- for ( i = 1 ; i <= 9 ; i++ )
- v1.push_back( i );
- random_shuffle( v1.begin( ), v1.end( ) );
- cout << "Vector v1 is ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")." << endl;
- // Make v1 a heap with default less than ordering
- make_heap ( v1.begin( ), v1.end( ) );
- cout << "The heaped version of vector v1 is ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")." << endl;
- // Add an element to the heap
- v1.push_back( 10 );
- cout << "The heap v1 with 10 pushed back is ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")." << endl;
- push_heap( v1.begin( ), v1.end( ) );
- cout << "The reheaped v1 with 10 added is ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")." << endl << endl;
- // Make v1 a heap with greater than ordering
- make_heap ( v1.begin( ), v1.end( ), greater<int>( ) );
- cout << "The greater-than heaped version of v1 is/n ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")." << endl;
- v1.push_back(0);
- cout << "The greater-than heap v1 with 11 pushed back is/n ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")." << endl;
- push_heap( v1.begin( ), v1.end( ), greater<int>( ) );
- cout << "The greater than reheaped v1 with 11 added is/n ( " ;
- for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
- cout << *Iter1 << " ";
- cout << ")." << endl;
- }
发现竟然在push_heap()那里抛了异常。(invalid Heap)
然后无奈去了www.cplusplus.com也下了一段代码:
- // range heap example
- #include <iostream>
- #include <algorithm>
- #include <vector>
- using namespace std;
- int main () {
- int myints[] = {10,20,30,5,15};
- vector<int> v(myints,myints+5);
- vector<int>::iterator it;
- make_heap (v.begin(),v.end());
- cout << "initial max heap : " << v.front() << endl;
- pop_heap (v.begin(),v.end()); v.pop_back();
- cout << "max heap after pop : " << v.front() << endl;
- v.push_back(99); push_heap (v.begin(),v.end());
- cout << "max heap after push: " << v.front() << endl;
- sort_heap (v.begin(),v.end());
- cout << "final sorted range :";
- for (unsigned i=0; i<v.size(); i++) cout << " " << v[i];
- cout << endl;
- return 0;
- }
这段代码没有抛异常,运行完好。仔细检查一番,发现可能是vector数组中的元素没有增多的缘故。于是将
pop_heap (v.begin(),v.end()); v.pop_back();改为
pop_heap (v.begin(),v.end()); 这样vector元素就在总数上多了一。
然后运行..相同的错误。
不知道vs2008版本上有没有相同的错误。