top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C++: Accessing the top of the stack and applying the operations?

+2 votes
291 views
#include <iostream>
#include <stack>

using namespace std;
int main ()
{
        stack<int> mystack;
        mystack.push(10);
        mystack.push(20);
        mystack.top() -= 5;
        cout << mystack.top() << endl;
        return 0;
}
posted Sep 29, 2014 by Muskan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

This is the definition of the top function

reference& top();

Which means it returns the reference to the top of the stack so following operation will change the value of the top itself

    mystack.top() -= 5;

Hence cout << mystack.top() << endl; will print the value of the top as 15.

answer Sep 29, 2014 by Salil Agrawal
Similar Questions
+2 votes

suppose we have an array of N natural numbers and asks him to solve the following queries:-
Query a:- modify the element present at index i to x.
Query b:- count the number of even numbers in range l to r inclusive.
Query c:- count the number of odd numbers in range l to r inclusive.

input:
First line of the input contains the number N. Next line contains N natural numbers.Next line contains an integer Q followed by Q queries.
a x y - modify the number at index x to y.
b x y - count the number of even numbers in range l to r inclusive.
c x y - count the number of odd numbers in range l to r inclusive.
I tried to solve using simple arrays but it isn't doing well for big constraints so I thought to use other DS with efficient algorithm so please explain appropriate algorithm.Thanks in advance.

+1 vote

I have a need for certain functions in a shared library to know the path to that library in order to find various resources. What I have in source.cpp:

#include 
#include 
static std::string myPath;

__attribute__((constructor))
void SetPath() {
 Dl_info dl_info;
 dladdr((void*)SetPath, 
 myPath = dl_info.dli_fname; // 

As the comment shows, when built with optimizations enabled, that line produces a segfault. With no optimizations, it works just fine. What magic must be done in order to ensure that this variable exists before the "constructor" function is called when loading the shared library?

0 votes

How can I write an ASSEMBLER in C programming language for calculating mathematical operations?

...