title: implementation of stacks using vector - segmentation fault in peek() function
body: <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  using namespace std;
  
  class Stack{
    public:
    vector&lt;string&gt; vc;
    int length=0;
  
    void peek(){
       if(vc.size()==0){
           cout&lt;&lt; &quot;The stack is empty&quot;&lt;&lt;endl;
       }
       cout&lt;&lt; vc[length]&lt;&lt;endl; //----&gt; does not work;
       //cout&lt;&lt;vc[vc.size()-1]; ---&gt; does not work either
       //cout&lt;&lt;vc.end(); ----&gt; does not work either;
    }
  
    void add(string value){
        vc.push_back(value);
        length++;
    }
  
    void pop(){
        vc.erase(vc.end());
        length--;
    }
  
    void show(){
      for (int i=0;i&lt;vc.size();i++){
          cout &lt;&lt; vc[i] &lt;&lt; &quot; &quot;;
      }
      cout&lt;&lt;endl;
    }
  
  
  };
  
  int main()
  {
      Stack mystack;
      mystack.peek();
      mystack.add(&quot;Hello&quot;);
      mystack.peek();
      mystack.add(&quot;frands&quot;);
      mystack.add(&quot;chai&quot;);
      mystack.add(&quot;pee&quot;);
      mystack.add(&quot;lo&quot;);
      mystack.show();
      mystack.peek();
      mystack.pop();
      mystack.show();
  }
  </code></pre>
  <p>problem 1-&gt;
  the problem arises in the peek() function i cannot access the last element in my vector space i get returned with a segmentation fault(core dump) error.</p>
  <p>problem 2-&gt;
  and while pasting this code on stack overflow i had to manually add 4spaces in each code line how to do this at one step (sorry for a silly question).</p>