2014-04-08 58 views
0

關於make_heap功能的問題。
stl使用make_heap
需要v.begin()v.end() // [front, end)
,但如果我不希望到堆加10是什麼使得一個堆..make_heap()函數參數 - 如果我不想包含某些元素,該怎麼辦?

我想我可以做到這一點使用:

make_heap(v.begin(),v.end()-1); 

但這沒有給我任何的不同輸出..我試着用make_heap(v.begin(),v.end()-1);代替make_heap(v.begin(),v.end());
但輸出是一樣的...

這裏發生了什麼..

代碼#1:

#include <algorithm>  
#include <vector>  


int main() { 
    int myints[] = {1,2,3,4,5,6,7,8,9,10}; 
    std::vector<int> v(myints,myints+10); 




    std::make_heap (v.begin(),v.end()); 
    std::cout << "range :"; 
    for (unsigned i=0; i<v.size(); i++) 
    std::cout << ' ' << v[i]; 

    std::cout << '\n'; 

    return 0; 
} 

代碼#2:

#include <algorithm> 
#include <vector>  

int main() { 
    int myints[] = {1,2,3,4,5,6,7,8,9,10}; 
    std::vector<int> v(myints,myints+10); 




    std::make_heap (v.begin(),v.end()-1); 

    std::cout << "range :"; 
    for (unsigned i=0; i<v.size(); i++) 
    std::cout << ' ' << v[i]; 

    std::cout << '\n'; 

    return 0; 
} 

兩個給我相同的輸出.. (?)

+0

編譯器?版?在coliru的g ++ 4.8.2爲這兩個程序提供了不同的輸出。 [Live example](http://coliru.stacked-crooked.com/a/0228874747550608) – dyp

+0

哦,我想我知道了..它仍然打印出所有10個元素,因爲我使用v.size()和v [我]打印元素..所以基本上make_heap()只是命令矢量v中的元素..不創建一個新的矢量本身..正確?... – psj01

+2

它仍然不應該給你*相同的*輸出。第二個程序不應該移動元素「10」,所以它應該停留在最後。第一個程序需要把這個元素放在前面。 – dyp

回答

1

這不是每個說的答案,但我無法重現您的結果:我獲得兩個不同的輸出。

計劃:

#include <algorithm> 
#include <vector> 
#include <iostream> 

void code1() 
{ 
    int myints[] = {1,2,3,4,5,6,7,8,9,10}; 
    std::vector<int> v(myints,myints+10); 

    std::make_heap (v.begin(),v.end()); 
    std::cout << "range :"; 
    for (unsigned i=0; i<v.size(); i++) 
    std::cout << ' ' << v[i]; 

    std::cout << '\n'; 
} 

void code2() 
{ 
    int myints[] = {1,2,3,4,5,6,7,8,9,10}; 
    std::vector<int> v(myints,myints+10); 

    std::make_heap (v.begin(),v.end()-1); 
    std::cout << "range :"; 
    for (unsigned i=0; i<v.size(); i++) 
    std::cout << ' ' << v[i]; 

    std::cout << '\n'; 
} 

// ------------------------------------------------------------------------ 

int main() 
{ 
    code1(); 
    code2(); 
} 

編譯&輸出:

[email protected]:/tmp$ g++ --version 
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 
Copyright (C) 2011 Free Software Foundation, Inc. 
This is free software; see the source for copying conditions. There is NO 
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 

[email protected]:/tmp$ g++ -o so2 so2.cpp 
[email protected]:/tmp$ ./so2 
range : 10 9 7 8 5 6 3 1 4 2 
range : 9 8 7 4 5 6 3 2 1 10 
[email protected]:/tmp$ 
相關問題