Grupo
Estructuras de Datos: Pilas y Colas en C++
Ojetivo
1. Implementar una pila para almacenar valores (verdaderos o falsos) durante la evaluación.
2. Leer una expresión lógica que contenga los operadores: AND (&&), OR (||) y NOT (!).
3. Usar la pila para evaluar la expresión procesando los operandos y operadores uno por uno.
4. Tras procesar todos los operadores y operandos, generar el resultado final como verdadero o falso.
5. Gestionar expresiones lógicas básicas con la precedencia de operadores adecuada.
Implementar una pila para evaluar expresiones lógicas.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include for input/output operations
#include <stack> // Include for stack operations
#include <string> // Include for string manipulations
#include <sstream> // Include for stringstream operations
using namespace std;
// Function to evaluate logical expressions
bool evaluateLogicalExpression(string expr) {
stack s; // Stack to store boolean values (true/false)
stringstream ss(expr); // Stringstream to process the expression
string token; // To store individual tokens (operand or operator)
// Process each token in the expression
while (ss >> token) {
if (token == "true") {
s.push(true); // Push true onto the stack
} else if (token == "false") {
s.push(false); // Push false onto the stack
} else if (token == "&&") {
bool b2 = s.top(); s.pop(); // Pop the second operand
bool b1 = s.top(); s.pop(); // Pop the first operand
s.push(b1 && b2); // Perform AND operation and push the result
} else if (token == "||") {
bool b2 = s.top(); s.pop(); // Pop the second operand
bool b1 = s.top(); s.pop(); // Pop the first operand
s.push(b1 || b2); // Perform OR operation and push the result
} else if (token == "!") {
bool b = s.top(); s.pop(); // Pop the operand
s.push(!b); // Perform NOT operation and push the result
}
}
// Return the final result (the top element of the stack)
return s.top();
}
// Main function to test the logical expression evaluation
int main() {
string expr = "true false && true || ! false &&"; // Example logical expression
// Evaluate the expression
bool result = evaluateLogicalExpression(expr);
// Output the result
cout << "Result of the logical expression: " << (result ? "true" : "false") << endl;
return 0;
}
Salida
Result of the logical expression: true
Comparte este ejercicio C++