In the following code, I am getting the segmentation fault. Whenever the query type is 1, we have to push element into the stack, if it is 2 then we have to pop from stack, and if it is 3 then print the maximum value in the stack.
My guess is that the error is present somewhere in the switch case. However, I am unable to spot it. Please help.
#include<bits/stdc++.h>
using namespace std;
int maxinStack(stack<int> st){
int max=st.top();
for (int i=0;i<st.size();i++){
if(st.top()>max){
max=st.top();
}
st.pop();
}
return max;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
stack<int> s;
int querySize;
cin >> querySize;
vector<int> queryType(querySize);
queue<int> queryData;
for(int i=0;i<querySize;i++){
cin>>queryType[i];
if(queryType[i]==1){
int x;
cin >> x;
queryData.push(x);
}
}
/*for (int j=0;j<querySize;j++){
cout << queryType.at(j)<<" ";
}
cout << endl;
while(!queryData.empty()){
cout << queryData.front()<<" ";
queryData.pop();
}
cout << endl;
*/
for (int j=0;j<querySize;j++){
switch (queryType[j]){
case 1:{
int y=queryData.front();
s.push(y);
queryData.pop();
}
case 2: s.pop();
case 3: cout << maxinStack(s)<<endl;
}
}
return 0;
}
Assuming inputs are correct, I think you forgot to put break at the end of each case handlers.
So it should be something like:
switch (queryType[j]){
case 1:{
int y=queryData.front();
s.push(y);
queryData.pop();
break;
}
case 2: s.pop(); break;
case 3: cout << maxinStack(s)<<endl; break;
}
Otherwise when it handles case 1 it will still fall-through to the next case handlers so it also does case 2 and case 3. This means that the stack is always empty and it causes segmentation fault when it handles query type of 2 - tried to pop for an empty stack.
As pointed above by #Hanjoung, your switch cases are missing break statements. Just to give you a little context on these break statements, if not specified all the cases after the matched case will also run. For eg:
switch(choice){
case 1:
case 2: // Suppose this case matched
case 3: // This will also run as no break in case 2
break;
case 4: // Will not run as break in case 3
default:
}
The reason you are getting segmentation error is because your "case 2" is popping from empty stack, and reason for running of this "case 2" is absence of break statement in "case 1".
Related
I need to exit the loop, if one of my queue elements satisfies a condition. putting break results in a compile error. what is the best way to execute the loop parallel
//code
std::deque<element> my_elements;
std::for_each(std::execution::par_unseq, my_elements.begin(), my_elements.end(),
[&](auto v) {
if (v.attribute == something)
{
break;
}
});
I'm pretty sure that won't work. Why? because break is a statically scoped operation; i.e, the destination for the break is determined at compile time. Putting it into a lambda (w the loop external to the lambda) makes it impossible for the compiler to see where to "break to".
Example w/o parallelism:
vector<int> v {1,2,3,4,5,6,7,8,9};
std::for_each(v.begin(), v.end(),
[](int i) { cout << i << ' '; if (i == 5) break; });
cout << endl;
gives me the following error:
so.cpp:10:45: error: 'break' statement not in loop or switch statement
[](int i) { cout << i << ' '; if (i == 5) break; });
To answer your question; I don't think there's a good way to break out of for_each in a parallel algorithm. For the non-parallel case, you could throw an exception, but that won't work in the parallel case.
How can we calculate Big O of switch statement whom are having function calls in there cases. that Function can be the Function in whom the switch statement is present and can also direst to another function whom can send it back to the same Switch statement.
void ifpascorrectSwitch(int *currentbalance) {
cout << "\n\n";
cout << "Current balance = £" << *currentbalance << endl;
string casee;
cout << "Enter any of the below option\n"
"1 for Deposit cash \n"
"2 for Withdraw cash\n"
"e for Quiting the application\n"
"= ";
cin >> casee;
if (casee.length() == 1) {
const char *k = casee.c_str(); // character inter to a c string
switch (*k) {
case '1':
cout << "1 Deopist cash \n";
Depositcash(currentbalance);
//Deposit is another function call whom can can come back to this function
// and have this switch menu again because of bellow given //ifpascorrectSwitch(currentbalance) which is function call of the current //function
ifpascorrectSwitch(currentbalance);
break;
case '2':
cout << "2 Withdraw menu\n";
WithdrawCash(currentbalance);
ifpascorrectSwitch(currentbalance);
break;
case 'e':
cout << "r is working";
break;
default:
cout << "Default switch wrong entery";
ifpascorrectSwitch(currentbalance);
break;
}
} else {
cout << "Wrong entery please try again";
ifpascorrectSwitch(currentbalance);
} }
All other function call other then ifpascorrectSwitch(currentbalance)which is current function call are having same scenario of switch stament. almost.
If only someone could help me atleast undesrtanding this Switch statement Big O calcultaion.
I want to switch over possible values of two integers, or in another case two bools. For the sake of discussion, suppose I've done
auto mypair = std::make_pair(foo, bar);
How can I achieve the equivalent of
switch(mypair) {
case make_pair(true, false): cout << "true and false"; break;
case make_pair(false, true) cout << "false and true"; break;
case default: cout << "something else";
}
with C++11? (C++14/17 also relevant if that helps)?
You can only switch on an integral type, but if you can devise a function to map your pair (or any complex type) to an integral type, you can declare it as constexpr (C++11) to indicate it can be resolved at compile time. Then it is acceptable as a case expression.
Simple example:
enum Action { peel, eat, juice };
enum Fruit { apple, orange, banana };
constexpr unsigned int switch_pair(Action a, Fruit f) {
return (a << 16) + f;
}
Then define the switch like this:
switch(switch_pair(mypair.first,mypair.second))
{
case switch_pair(peel,apple): std::cout << "Peeling an apple" << std::endl; break;
case switch_pair(eat,apple): std::cout << "Eating an apple" << std::endl; break;
case switch_pair(juice,apple): std::cout << "Juicing an apple" << std::endl; break;
default:
throw std::runtime_error("We only have apples!");
}
C++'s switch statement doesn't have the pattern matching power of many other languages. You'll need to take a slightly different approach.
Here's a possibility I threw together:
pair_switch(my_pair,
std::make_tuple(true, false, []{ std::cout << "true and false"; }),
std::make_tuple(false, true, []{ std::cout << "false and true"; }));
You supply a std::pair<bool,bool> and a set of cases as std::tuples, where the first two elements match the pair you pass in and the third element is a function to call for that case.
The implementation has a few template tricks, but should be pretty usable:
template <typename... Ts>
void pair_switch(std::pair<bool,bool> pair, Ts&&... ts) {
//A table for the cases
std::array<std::function<void()>, 4> table {};
//Fill in the cases
(void)std::initializer_list<int> {
(table[std::get<0>(ts)*2 + std::get<1>(ts)] = std::get<2>(ts), 0)...
};
//Get the function to call out of the table
auto& func = table[pair.first*2 + pair.second];
//If there is a function there, call it
if (func) {
func();
//Otherwise, throw an exception
} else {
throw std::runtime_error("No such case");
}
}
Live Demo
Im trying to make a recursive menu.
This program will later work with a tree(hojanodo), thats why I keep track of the root.
Problem: For some reason the fgets/fgetc is being skipped inside the recursivity on the second run, why does this happen?
I want the user to input either 1,2 or 3.(int)
What would be the fix for this? and is this the best way to implement a menu?
Here's what I have right now:(It compiles and runs so you can test it out but doesn't really work like I would like to..)
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
char ch;
int i;
struct node *left;
struct node *right;
}hojaNodo;
int handle_menu(int eventHandler, hojaNodo **root);
int opcion_menu();
char get_symbol();
int get_userMenuInput();
int intro();
int main(){
hojaNodo *treeRoot = NULL;
intro();
// system("clear");
handle_menu(opcion_menu(), &treeRoot);
return 0;
}
int opcion_menu(){
int userOption;
printf("1.Agrega un Simbolo.\n");
printf("2.Listar Codigo\n");
printf("3.Exit");
userOption = get_userMenuInput();
printf("User: %d",userOption);
if(userOption < 4 && userOption > 0){
return userOption;
}
else
return -1;
}//eof opcion_menu
int handle_menu(int userOption,hojaNodo **root){
hojaNodo *tempRoot = NULL;
tempRoot = *root;
int valor;
char simbol;
switch(userOption){
case 1:
simbol = get_symbol();
printf("Simbol: %c", simbol);
break;
case 2:
printf("List Nodes\n");
break;
case 3:
printf("Exit");
userOption = -1;
// destroy_tree(root);
break;
default:
printf("userOption Error, Bye!");
break;
}//eof switch
if(userOption != -1)
handle_menu(opcion_menu(),&tempRoot);
// return userOption;
return -1;
}//eof menu()
char get_symbol(){
/*char userKey[3]
fgets(userKey,len,stdin);*/
char simbolo;
printf("Give me a symbol.");
simbolo = fgetc(stdin);
return simbolo;
}
int get_userMenuInput(){
char userKey[3];
int userOption;
size_t len;
len = sizeof(userKey);
fgets(userKey,len,stdin);
userOption = atoi(userKey);
//printf("User Option: %d\n", userOption);
return userOption;
}
Well apart from all the comments related to recursion and other changes suggested, please check this out. fgets() function needs flushing the input stream. It can be done using fflush() or fgetc().
A simple solution would be:
In function:
int opcion_menu(){
...
fgets(userKey,2,stdin);
fgetc(stdin); // Add this statement
Also in function:
int handle_menu(int userOption,hojaNodo **root)
case 1:
printf("Give me a choice : ");
fgets(userKey,2,stdin);
fgetc(stdin); // add this statement
fgets reads in at most one less than size characters from stream and stores them into the buffer pointed to by string. This will lead the newline character still available in Input Stream which need to be flushed. If this newline character is not read from Input stream, than this would become the input for next fgets function and ultimately it will skip the fgets(since it has already got its input a newline character)
fgetc(stdin) will flush out these extra newline character.
I don't know if this might help anyone.
In my case, I had to 'free' the buffer from the char with this function:
void clean(){
char cTemp;
while((cTemp = getchar()) != '\n')
;
}
Im not really sure why this works but it does(if anyone does, please add it to my answer).
I call it right before I call get_userOption();
I write a small program about B-Trix. And I want to use getch() to get gamer's input.
I try to get the value of up,down,right,left key-press by using getch(), here is my test code:
#include <stdio.h>
#include <curses.h>
int main(void)
{
int ch;
initscr();
printw("Input a character:");
ch = getch();
printw("\nYou input a '%c'\n%d", ch, ch);
refresh();
sleep(3);
endwin();
return 0;
}
the outputs of up down left right are 27, why are these value same?
Could anybody help me?
The arrow keys were encoded by three characters in Ubuntu.
So I changed my code like this to check arrow keys.
if(kbhit()){
switch(getch()){
case 0x1b: //For case arrow pressed
if(getch() == 0x5b){
switch(getch()){
case 0x41:
turn();
break;
case 0x44:
mv_left();
break;
case 0x43:
mv_right();
break;
case 0x42:
mv_down();
break;
}
}
break;
}
}