這裏在我的代碼中,程序不能變量n,我感到它爲什麼會發生?爲什麼程序看不到全局變量?
#include<iostream>
#include<vector>
using namespace std;
int d=3;
int n=12;
template<class T>
class pqi
{
vector<int>pq;
vector<int>qp;
vector<T>&a(n);
void exch(int i,int j)
{
int t=pq[i];
pq[i]=pq[j];
pq[j]=t;
qp[pq[i]]=i;
qp[pq[j]]=j;
}
void fixup(int k)
{
while(k>1 && a[pq[(k+d-2)/d]]>qp[pq[k]])
{
exch(k,(k+d-2)/d);k=(k+d-2)/d;
}
}
void fixdown(int k,int n)
{
int j;
while((j=d*(k-1)+2)<=n)
{
for(int i=j+1;i<j+d&& i<=n;i++)
if(a[pq[j]]>a[pq[i]]) j=i;
if(!(a[pq[k]]>a[pq[j]])) break;
exch(k,j);k=j;
}
}
public:
pqi(int n,const vector<T>&a,int d=3):a(a),pq(n+1,0),qp(n+1,0),n(0),d(d){}
int empty() const
{
return n==0;
}
void insert(int v)
{
pq[++n]=v ;
qp[v]=n;
fixup(n);
}
int getmin()
{
exch(1,n);
fixdown(1,n-1);
return pq[--n];
}
void lower(int k)
{
fixup(qp[k]);
}
};
int main()
{
vector<int>s(n);
pqi<int>a(n,s,d);
for(int i=0;i<12;i++)
a.insert(rand()%(RAND_MAX+i));
while(!a.empty())
{
cout<<a.getmin()<<" ";;
}
return 0;
}
我已宣佈的代碼作爲全局變量外,butit can'see並說
1>c:\users\\documents\visual studio 2012\projects\multiway_heap\multiway_heap\multiway_heap.cpp(12): error C2061: syntax error : identifier 'n'
1> c:\users\\documents\visual studio 2012\projects\multiway_heap\multiway_heap\multiway_heap.cpp(62) : see reference to class template instantiation 'pqi<T>' being compiled
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
我真的無法理解這樣的行爲,請大家幫我澄清我做錯了
什麼是line'vector &a(n);'應該這樣做? –
http://www.scribd.com/doc/83085976/53/Program-20-10-Multiway-heap-PQ-implementation –
除了在答案中指出的明顯問題,您正試圖初始化兩個不存在yout''pqi''構造函數中的成員變量,即''n''和''d''。 – juanchopanza