关于make_heap
功能的问题
使用stl
时在make_heap
中制作堆时
它需要v.begin()
和v.end()
// [front, end)
但是如果我不想在堆中添加10个怎么办呢?
我认为我可以通过使用:
来实现这一目标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 :(得分: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();
}
编译&amp;输出:
john@---:/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.
john@---:/tmp$ g++ -o so2 so2.cpp
john@---:/tmp$ ./so2
range : 10 9 7 8 5 6 3 1 4 2
range : 9 8 7 4 5 6 3 2 1 10
john@---:/tmp$