std::stack<std::string> words;stack 容器适配器的模板有两个参数。第一个参数是存储对象的类型,第二个参数是底层容器的类型。stack<T> 的底层容器默认是 deque<T> 容器,因此模板类型其实是 stack<typename T, typename Container=deque<T>>。通过指定第二个模板类型参数,可以使用任意类型的底层容器,只要它们支持 back()、push_back()、pop_back()、empty()、size() 这些操作。下面展示了如何定义一个使用 list<T> 的堆栈:
std::stack<std::string,std::list<std::string>> fruit;创建堆栈时,不能在初始化列表中用对象来初始化,但是可以用另一个容器来初始化,只要堆栈的底层容器类型和这个容器的类型相同。例如:
std::list<double> values {1.414, 3.14159265, 2.71828};
std::stack<double,std::list<double>> my_stack (values);
第二条语句生成了一个包含 value 元素副本的 my_stack。这里不能在 stack 构造函数中使用初始化列表;必须使用圆括号。如果没有在第二个 stack 模板类型参数中将底层容器指定为 list,那么底层容器可能是 deque,这样就不能用 list 的内容来初始化 stack;只能接受 deque。
std::stack<double,std::list<double>>copy_stack {my_stack}
copy_stack 是 my_stack 的副本。如你所见,在使用拷贝构造函数时,既可以用初始化列表,也可以用圆括号。
inline size_t precedence(const char op)
{
if (op == '+' || op =='-')
return 1;
if (op == '*' || op == '/')
return 2;
if (op =='^')
return 3;
throw std:: runtime_error {string{"invalid operator: "} + op};
}
+ 和 - 的优先级最低,其次是 * 和 /,最后是 ^。运算符的优先级决定了它们在表达式中的执行顺序。如果参数是一个不支持的运算符,那么会拋出一个 runtime_error 异常对象。异常对象构造函数中的字符串参数,可以在 catch 代码块中通过调用对象的 what() 函数获得。
double execute(std::stack<char>& ops, std::stack<double>& operands)
{
double result {};
double rhs {operands.top()}; // Get rhs...
operands.pop(); // ...and delete from stack
double lhs {operands.top()}; // Get lhs...
operands.pop(); // ...and delete from stack
switch (ops.top()) // Execute current op
{
case '+':
result = lhs + rhs;
break;
case '-':
result = lhs - rhs;
break;
case '*':
result = lhs * rhs;
break;
case '/':
result = lhs / rhs;
break;
case '^':
result = std::pow(lhs, rhs);
break;
default:
throw std::runtime_error {string{"invalid operator: "} + ops.top()};
}
ops.pop(); // Delete op just executed
operands.push(result);
return result;
}
函数的参数是两个 stack 容器的引用。可以用 operands 容器的 top() 函数获取操作数。 top() 函数只能得到栈顶元素;为了访问下一个元素,必须通过调用 pop() 来移除当前栈顶元素。
// A simple calculator using stack containers
#include <cmath> // For pow() function
#include <iostream> // For standard streams
#include <stack> // For stack<T> container
#include <algorithm> // For remove()
#include <stdexcept> // For runtime_error exception
#include <string> // For string class
using std::string;
// Returns value for operator precedence
inline size_t precedence(const char op)
{
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
if (op == '^')
return 3;
throw std::runtime_error {string {"invalid operator in precedence() function: "} + op};
}
// Execute an operation
double execute(std::stack<char>& ops, std::stack<double>& operands)
{
double result {};
double rhs {operands.top()}; // Get rhs...
operands.pop(); // ...and delete from stack
double lhs {operands.top()}; // Get lhs...
operands.pop(); // ...and delete from stack
switch (ops.top()) // Execute current op
{
case '+':
result = lhs + rhs;
break;
case '-':
result = lhs - rhs;
break;
case '*':
result = lhs * rhs;
break;
case '/':
result = lhs / rhs;
break;
case '^':
result = std::pow(lhs, rhs);
break;
default:
throw std::runtime_error {string{"invalid operator: "} + ops.top()};
}
ops.pop(); // Delete op just executed
operands.push(result);
return result;
}
int main()
{
std::stack<double> operands; // Push-down stack of operands
std::stack<char> operators; // Push-down stack of operators
string exp; // Expression to be evaluated
std::cout << "An arithmetic expression can include the operators +, -, *, /, and ^ for exponentiation." << std::endl;
try
{
while (true)
{
std::cout << "Enter an arithmetic expression and press Enter - enter an empty line to end:" << std::endl;
std::getline(std::cin, exp, '\n');
if (exp.empty()) break;
// Remove spaces
exp.erase(std::remove(std::begin(exp), std::end(exp), ' '), std::end(exp));
size_t index {}; // Index to expression string
// Every expression must start with a numerical operand
operands.push(std::stod(exp, &index)); // Push the first (lhs) operand on the stack
while (true)
{
operators.push(exp[index++]); // Push the operator on to the stack
// Get rhs operand
size_t i {}; // Index to substring
operands.push(std::stod(exp.substr(index), &i)); // Push rhs operand
index += i; // Increment expression index
if (index == exp.length()) // If we are at end of exp...
{
while (!operators.empty()) // ...execute outstanding ops
execute(operators, operands);
break;
}
// If we reach here, there's another op...
// If there's a previous op of equal or higher precedence execute it
while (!operators.empty() && precedence(exp[index]) <= precedence(operators.top()))
execute(operators, operands); // Execute previous op.
}
std::cout << "result = " << operands.top() << std::endl;
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
std::cout << "Calculator ending..." << std::endl;
}
while 循环包含在一个 try 代码块中,这样就可以捕获抛出的任何异常。在 catch 代码块中,调用异常对象的成员函数 what() 会将错误信息输出到标准错误流中。在一个死循环中执行输入操作,当输入一个空字符串时,循环结束。可以使用 remove() 算法消除非空字符串中的空格。remove() 不能移除元素,而只能通过移动元素的方式来覆盖要移除的元素。
An arithmetic expression can include the operators +, -, *, /, and ^ for exponentiation.
Enter an arithmetic expression and press Enter - enter an empty line to end:
2^0.5
result = 1.41421
Enter an arithmetic expression and press Enter - enter an empty line to end:
2.5e2 + 1.5e1*4
result = 310
Enter an arithmetic expression and press Enter - enter an empty line to end:
3*4*5 + 4*5*6 + 5*6*7
result = 390
Enter an arithmetic expression and press Enter - enter an empty line to end:
Calculator ending...
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有