最近在研究C++標準看到make_heap的範例用法。
連結: http://en.cppreference.com/w/cpp/algorithm/make_heap
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> v { 3, 1, 4, 1, 5, 9 };
std::cout << "initially, v: ";
for (auto i : v) std::cout << i << ' ';
std::cout << '\n';
std::make_heap(v.begin(), v.end());
std::cout << "after make_heap, v: ";
for (auto i : v) std::cout << i << ' ';
std::cout << '\n';
std::pop_heap(v.begin(), v.end());
auto largest = v.back();
v.pop_back();
std::cout << "largest element: " << largest << '\n';
std::cout << "after removing the largest element, v: ";
for (auto i : v) std::cout << i << ' ';
std::cout << '\n';
}
網站直接Run Code運行結果:
initially, v: 3 1 4 1 5 9
after make_heap, v: 9 5 4 1 1 3
largest element: 9
after removing the largest element, v: 5 3 4 1 1
覺得很奇怪的地方是,範例中排序的結果怪怪的。
after make_heap, v: 9 5 4 1 1 3 應該是 9 5 4 3 1 1才對吧?
自己又用VC2015運行一次,發現結果一樣
是我哪邊誤解了嗎??
懇請解答~