C ++ Stack top()函数的作用是:返回栈顶元素的值。顶部元素是最近添加到堆栈中的元素。最后添加的元素是顶部元素。在堆栈中出现的所有元素中,top元素最为突出,并且更重要,因为堆栈上的所有主要操作都在top元素上执行。无论是推入、弹出还是其他操作,所有操作都是在最上面的位置完成的。
value_type& top(); const value_type& top() const;
该函数仅用于返回top元素的值,因此不带任何参数。函数的返回类型基于堆栈的值类型。
该函数返回堆栈的顶部元素。
//程序说明了堆栈中top()函数的使用,以检索最上面的元素的值。
#include <iostream>
#include <stack>
int main()
{
std::stack<int> newstack;
newstack.push(24);
newstack.push(80);
newstack.top () +=20;
std::cout <<"newstack.top() 修改为" <<newstack.top ();
return 0;
}输出:
newstack.top() 修改为 100
//程序说明了堆栈中top()函数的使用,以检索最上面的元素的值。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
int result = 0;
stack<int> newstack;
newstack.push(2);
newstack.push(7);
newstack.push(4);
newstack.push(5);
newstack.push(3);
while(!newstack.empty() )
{
result = result + newstack.top();
newstack.pop();
}
cout<<result;
return 0;
}输出:
21
//程序说明了堆栈中top()函数的使用,以检索最上面的元素的值。
#include <iostream>
#include <stack>
int main ()
{
std::stack<int> newstack;
newstack.push(9);
newstack.push(14);
std::cout << "newstack.top() is " << newstack.top() << '\n';
return 0;
}输出:
newstack.top() is 14
函数的复杂性是恒定的。该函数仅检索top元素的值,而不花费任何额外的时间或空间。
该函数访问容器,并检索最后插入的元素。给出了堆栈中最顶层的元素。
提供与在底层容器对象上执行的操作等效的保证。