簡體   English   中英

使用Vector實現Stack的問題

[英]Problem in implementing Stack using Vector

在課堂上說:

class X
{
     int _top;
     vector<int> _stack;
public:
     X() { } // SOME CONSTRUCTOR
};

這種形式的構造函數為何起作用:

X( int capacity )
     : _stack( capacity ), _top( 0 ) { }

但是這些不起作用:

1。

X( int capacity )
{ _stack( capacity );  _top=0; }

2。

X( int capacity )
     {_stack = capacity;  _top=0;}

請解釋。

第一種有效,因為您正在初始化列表中初始化_stack ,而第二種形式不使用初始化列表。

閱讀此代碼中的注釋以了解什么是初始化列表!

struct sample
{
    int a,b,c; 
    vector<int> _stack;
    sample(int capacity) : _stack(capacity), a(1), b(10), c(100) {} 
           // ^^^^^^^^^^^^^^^^^^^^^ this is called initialization list  

    sample(int capacity, int x) 
    {
       _stack(capacity); //wrong!

       a = b = c = x; // this is called assignment
       //here, inside the constructor body you cannot 
       //initialize member variables, because members has been 
       //constructed and initialized already by the time executions comes here!
    } 
};

基本上,語法_stack(capacity)調用構造函數。 並且只有在構造對象時才能調用構造函數。 構造對象后,就無法調用構造函數。 在第二種形式中,您嘗試通過在構造函數主體中編寫_stack(capacity)來調用構造函數,但是到那時_stack已經被構造,這就是為什么您的代碼不起作用的原因!

有關初始化列表的詳細信息,請閱讀以下常見問題解答:

[10.6]我的構造函數應該使用“初始化列表”還是“分配”?

在第一種形式中,您要調用構造函數,但不能調用第二種和第三種。

1您正在調用vector<T>::operator ()(int) ,它沒有為vector<T>定義。

2您為vector<T>分配了一個int ,該int也未定義。

另外請記住, std::vector<int>(size_t n)構造函數不僅保留內存,還為向量填充n零。 如果您需要設置容量而不實際向向量添加任何值,請調用vector<T>::reserve(size_t)

如果這本身不是通過vector實現堆棧的目標,那么標准庫中已經可以使用std::stack容器適配器。

stack<int> myStack;

要么

stack<int, vector<int> > myVectorBasedStack;

這種形式有效,因為它調用了類成員的構造函數。

X( int capacity )
    : _stack( capacity ), //calls vector(int) constructor
    _top( 0 ) // calls int(int) constuctor
{ }

1.這是行不通的,因為一旦進入構造函數主體,就應使用其他語法調用構造函數。

X( int capacity )
{ 
    _stack( capacity ); //this is not a constuctor call. But this is vector operator()(int) call. And vector does not have this operator defined.
    //the proper constructor call in this place would be _stack = vector<int>( capacity );
    _top=0;
}

您可能將它與聲明和構造函數調用的縮短形式混淆了。 如果您聲明_stack為向量並同時進行初始化,則可以編寫:

vector<int> _stack( capacity );

但這只是以下形式的簡稱:

vector<int> _stack = vector<int>( capacity );

2.這是錯誤的,顯然是因為不能將整數賦給vector

X( int capacity ){ _stack = capacity;  _top=0; }

工作形式使用向量的構造函數-初始化列表中允許這樣做。

第一個無效的外觀似乎是您嘗試顯式調用vectors構造函數-不允許的,vector已經被構造。 初始化程序列表允許您使用顯式構造函數調用替換超類和成員變量的默認構造。

第三個不起作用,因為vector無法實現采用int的賦值運算符。 可以修改為_stack.resize(capacity)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM