2016-09-28 3 views
0

여기 내 코드가 있지만 이해할 수없는 한 가지 문제가 있습니다. 스택의 정수를 누를 때마다 나머지 (채워지지 않은 부분) 스택이 0 값으로 채워집니다. 제 잘못이 무엇인지 설명해주십시오. 내가 질문 권리를 얻을 매우 확실하지 않다배열을 기반으로 한 스택 구현

#include <iostream> 
using namespace std; 

class Stack 
{ 
private: 
    int* base; 
    int max_size; 
    int top; 

public: 
    Stack(int size = 100) 
    { 
     base = new int[size]; 
     max_size = size; 
     top = -1; 
    } 
    ~Stack() 
    { 
     delete[] base; 
    } 
    bool empty() const 
    { 
     return top == -1; 
    } 

    bool full() const 
    { 
     return top == max_size - 1; 
    } 

    void push(int element) 
    { 
     if (top == max_size-1) { 
      cout<< "Stack overflow" << endl; 
      return; 
     } 
     base[++top] = element; 
    } 

    void pop() 
    { 
     if(top == -1) { 
      cout << "Stack underflow" << endl; 
      return; 
     } 
     top--; 
    } 

    int & read_top() const 
    { 
     return base[top]; 
    } 

    void print() 
    { 
     int i = 0 ; 
     cout << "Stack is "; 
     while(i <= max_size) 
     { 
      cout << base[i] <<" "; 
      i++; 
     } 
     cout << endl; 
    } 
}; 

int main() 
{ 
    Stack first(10); 
    for(int i = 0; i<=5; i++) 
    { 
     first.push(i*i); 
     first.print(); 
    } 
    return 0; 
} 
+5

크기 ... – Jarod42

+2

[OT] 용량과하지 최대 귀하의'print' 표시 요소 : 당신은 돈 ' 존중 규칙 3/5/0. – Jarod42

+0

나는 처음에 쓰레기로 가득 찬 스택과 푸시 후 쓰레기로 가득 찬 채워진 부분을 실행했다. @ Jarod42 맞습니다. 관련 부분을 인쇄하려면 루프를 변경해야합니다. 하지만 코드에서 아무 것도 잘못되었습니다. 그리고 채워지지 않은 부분은 내 컴퓨터에 0을 가지고 있지 않습니다. – nrofis

답변

-2

: "나는 내 스택의 정수를 누를 때마다"당신은 무엇을 의미합니까? 내가 볼 수있는 한, 스택을 한 번 초기화 한 다음 그 사이의 서로 다른 배열을 변경하지 않고 푸시를 수행합니다. 여기서 일어나는 일은 배열이 0으로 초기화된다는 것입니다 (매번 컴파일러를 계산하지 않아도되지만 이번에는 최적화없이 컴파일 할 가능성이 높습니다). 그런 다음 하나의 요소를 추가하고 이미 누군가 당신은 스택만을 출력하지 않는다. (즉, 0에서부터 위로). 컴파일 된 최적화 된 경우, 0 대신 가비지 값을 얻을 수 있습니다. 배열은 생성자의 일부 초기 값으로 초기화되지 않으며 할당되지 않은 값은 값을 포함 할 수 있습니다. 희망이 도움이됩니다.

코드의 버그는 다음 print() 방법에 당신이해야 while(i < max_size)

+1

답변을 소리내어 답을 재구성하는 것을 고려하십시오. 지속적인 Q & A 포럼 게시물보다 덜 – bolov

+0

우수 설명을 주셔서 대단히 감사합니다. –

1

고려 : print에서

Stack s(10); 
for(int i = 0; i<=5; i++) 
    s.push(i); 

는 당신이 가지고 : 위의 경우

std::cout << "Stack is "; 
while(i <= max_size) 
    std::cout << base[i] << ' '; 

s.max_size입니다 10이므로 base [0,10]에 대한 값을 인쇄합니다.이 중 5 개는 초기화되지 않습니다. 앱이 아직 메모리를 많이 사용하지 않았기 때문에 할당을 수행 할 때 초기 (제로화) 메모리 블록을 얻을 가능성이 있습니다.

코드의 가능한 변화 :

#include <iostream> 
// using namespace std ; // unlearn the habbit of doing this. 
#include <memory> // for unique_ptr 

class Stack 
{ 
    // note: class is private by default. 
     // unique_ptr will automatically free memory for us. 
     using ptr_t = std::unique_ptr<int[]>; 

     ptr_t base_; 
     int* top_; 
     int* end_; 

    public : 
     Stack(int size=100) 
      : base_(new int[size]) 
      , top_(base_.get()) 
      , end_(top_ + size) 
     {} 

     bool empty() const 
     { return top_ == base_.get(); } 

     bool full() const 
     { return top_ == end_; } 

     // don't print errors from a library 
     bool push(int value) 
     { 
      if (full()) // written in terms of our own members 
       return false; 
      *(top_++) = value; 
      return true; 
     } 

     bool pop() 
     { 
      if (empty()) // written in terms of our own members 
       return false; 
      --top_; 
      return true; 
     } 

     const int& read_top() const // const ref so it's not modifiable 
     { return *(top_-1); } 

     int size() const { return end_ - top_; } 
     int capacity() const { return end_ - base_.get(); } 

     std::ostream& print(std::ostream& to) 
     { 
      to << "Stack is "; 
      for (int* ptr = base_.get(); ptr != top_; ++ptr) 
       to << *ptr << ' '; 
      to << '\n'; 
      return to; 
     } 

     // or we could do this: 
     friend std::ostream& operator << (std::ostream& to, const Stack& s) 
     { 
      to << '['; 
      for (int* ptr = s.base_.get(); ptr != s.top_; ++ptr) { 
       to << *ptr << ','; 
      } 
      return to << ']'; 
     } 
}; 

int main() 
{ 
    Stack s(5); 
    s.push(1); 
    s.push(2); 
    s.push(3); 
    s.print(std::cout); 
    std::cout << "stack is: " << s << '\n'; 
} 

라이브 데모 : http://ideone.com/JsA4EU