postfix evaluation algorithm - c++

here is my attempt for evaluation postfix evaluation
#include<iostream>
#include<string>
using namespace std;
template<class T>
class Stack
{
private:
T *s;int N;
public:
Stack(int maxn)
{
s=new T[maxn];
N=0;
}
int empty()const
{
return N==0;
}
void push(T k)
{
s[N++]=k;
}
T pop()
{
return s[--N];
}
};
int main()
{
//postfix evaluation
char *a="3+4*5";
int N=strlen(a);
Stack<int>save(N);
for(int i=0;i<N;i++)
{
if(a[i]=='+')
save.push(save.pop()+save.pop());
if(a[i]=='*')
save.push(save.pop()*save.pop());
if((a[i]>='0' && a[i]<='9'))
save.push(0);
while((a[i]>='0' && a[i]<='9'))
save.push(10*save.pop()+(a[i++]-'0'));
}
cout<<save.pop()<<" "<<endl;
return 0;
}
but instead of answer 23 because 4*5+3=23,it gives me answer 5,as i understood,this code gives me this result because,first it checks if there is + mark for i=0,which is not,then it checks if if it is *,this is also not,so it first push 0,then it evaluates 10*0+'3'-'0',which is equal to 3,(it would be pushed in stack),for i=1,a[i] is equal to 3,so it prints 3+, second pop is undefined,so i think it is error,please help me to fix it

This works with a little fix:
#include <iostream>
#include <cstring>
using namespace std;
template<class T>
class Stack
{
private:
T *s;
int N;
public:
Stack(int maxn)
{
s = new T[maxn];
N = 0;
}
int empty()const
{
return N == 0;
}
void push(T k)
{
s[N++] = k;
}
T pop()
{
return s[--N];
}
};
int main()
{
//postfix evaluation
const char *a = "3 4 5*+";
int N = strlen(a);
Stack<int>save(N);
for (int i = 0; i < N; i++)
{
if (a[i]=='+')
save.push(save.pop() + save.pop());
if (a[i]=='*')
save.push(save.pop() * save.pop());
if (a[i] >= '0' && a[i] <= '9')
{
save.push(0);
while (a[i] >= '0' && a[i] <= '9')
save.push(10 * save.pop() + a[i++] - '0');
i--;
}
}
cout << save.pop() << " " << endl;
return 0;
}
Output (ideone):
23
Now, if you remove that i--; which I added, the code will be skipping characters in a[] because of 2 increments of i, in a[i++] and for (int i = 0; i < N; i++).
Without i--; the output is (ideone):
9

Related

Process returned -1073741571 (0xC00000FD) on my c++ code [duplicate]

This question already has an answer here:
Clion exit code -1073741571 (0xC00000FD)
(1 answer)
Closed 2 years ago.
The c++ code below works fine for some inputs, but it is stuck at test 9 (number of inputs here is 6000) where it gives me this message "Process returned -1073741571 (0xC00000FD)".
This code reads information for n babies (their gender and name). Next it counts the appearances of each name then sorts the list of structures according to the appearances. Finally, it removes the duplicates and prints the top m female names and top m male names.
What does this error mean and what do I need to change to eliminate this error?
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string.h>
using namespace std;
ifstream fin("input.txt");
struct baby
{
string gender,name;
int cnt;
};
bool cmp(baby a,baby b)
{
if (a.cnt>b.cnt)
return true;
else if (a.cnt==b.cnt && a.name<b.name)
return true;
return false;
}
int howmany(baby babies[],int n,int i)
{
int cnt=0;
for (int j=0; j<n; j++)
{
if (babies[i].name==babies[j].name && babies[i].gender==babies[j].gender)
{
cnt++;
}
}
return cnt;
}
void getData(baby babies[],int n)
{
for (int i=0; i<n; i++)
{
fin>>babies[i].gender>>babies[i].name;
}
}
int removeDuplicates(baby babies[],int n)
{
int j=0;
for (int i=0; i<n-1; i++)
{
if (babies[i].name!=babies[i+1].name)
babies[j++]=babies[i];
}
babies[j++]=babies[n-1];
return j;
}
int main()
{
int n,i,top,j;
fin>>n>>top;
baby babies[50000];
getData(babies,n);
for (i=0; i<n; i++)
{
babies[i].cnt=howmany(babies,n,i);
}
sort(babies,babies+n,cmp);
j=removeDuplicates(babies,n);
int cnt=0;
for (int i=0; i<j; i++)
{
if (cnt<top)
{
if (babies[i].gender=="F")
{
cout<<babies[i].name<<" ";
cnt++;
}
}
}
cout<<endl;
cnt=0;
for (int i=0; i<j; i++)
{
if (cnt<top)
{
if (babies[i].gender=="M")
{
cout<<babies[i].name<<" ";
cnt++;
}
}
}
return 0;
}
As you can see in Window's NT status reference, error code 0xC00000FD means stack overflow (usually caused by infinite recursion). In your case, it seems that you simply allocate a far too large array on the stack (line 57, baby babies[50000];), which is an array of size 50000*20=1000000. The simplest solution will be a dynamic allocation
baby* babies = new baby[50000];
// Your code here
delete[] babies;
A better solution would be to use std::vector which is a dynamic array that can grow and shrink. The simplest thing to do is to take a vector of size 50000, this way:
#include <vector>
...
std::vector<baby> babies(50000);
However, this is a poor solution as your pre-allocate 50000 elements even though you probably need much much less, and a better solution would be to add an element on-demand, using .push_back(element) method, or in your case, allocate n elements to the vector (impossible in a stack-allocated array).
I added your code with some modifications of mine:
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("input.txt");
struct baby
{
string gender;
string name;
int cnt = 0;
};
bool cmp(const baby& a, const baby& b)
{
if (a.cnt > b.cnt) {
return true;
}
return a.cnt == b.cnt && a.name < b.name;
}
bool are_equal(const baby& lhs, const baby& rhs)
{
return lhs.gender == rhs.gender && lhs.name == rhs.name;
}
int howmany(const std::vector<baby>& babies, int i)
{
int cnt = 0;
for (int j = 0; j < babies.size(); j++)
{
if (babies[i].name == babies[j].name && babies[i].gender == babies[j].gender)
{
cnt++;
}
}
return cnt;
}
void getData(std::vector<baby>& babies)
{
for (int i = 0; i < babies.size(); i++)
{
fin >> babies[i].gender >> babies[i].name;
}
}
int removeDuplicates(std::vector<baby>& babies)
{
int j = 0;
for (int i = 0; i < babies.size() - 1; i++)
{
if (babies[i].name != babies[i + 1].name) {
babies[j++] = babies[i];
}
}
babies[j++] = babies.back();
return j;
}
void remove_duplicates_improved(std::vector<baby>& babies)
{
babies.erase(babies.begin(), std::unique(babies.begin(), babies.end(), are_equal));
}
int main()
{
int n;
int top;
fin >> n >> top;
std::vector<baby> babies(n);
getData(babies);
for (int i = 0; i < n; i++)
{
babies[i].cnt = howmany(babies, i);
}
sort(babies.begin(), babies.begin() + n, cmp);
remove_duplicates_improved(babies);
int cnt = 0;
for (int i = 0; i < babies.size(); i++)
{
if (cnt < top)
{
if (babies[i].gender == "F")
{
cout << babies[i].name << " ";
cnt++;
}
}
}
cout << endl;
cnt = 0;
for (int i = 0; i < babies.size(); i++)
{
if (cnt < top)
{
if (babies[i].gender == "M")
{
cout << babies[i].name << " ";
cnt++;
}
}
}
return 0;
}
Good luck

min-heap with zero based array C++

Below is my program to build a min-heap using a 0 based array with standard logic from the book. I am using 2*i+1 for left child and 2*i+2 for right child since its a zero based array, still I am getting a wrong output. What am I missing?
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
class HeapBuilder {
private:
vector<int> data_;
void WriteResponse() const {
for (int i = 0; i < data_.size(); ++i) {
cout << data_[i] << "\n";
}
}
void ReadData() {
int n;
cin >> n;
data_.resize(n);
for (int i = 0; i < n; ++i)
cin >> data_[i];
}
void MinHeapSort(int index)
{
int left = (2 * index) + 1;
int right = (2 * index) + 2;
int smallest;
if (left < data_.size() && data_[left] < data_[index])
smallest = left;
else
smallest = index;
if (right < data_.size() && data_[right] < data_[index])
smallest = right;
if (smallest != index)
{
swap(data_[smallest], data_[index]);
MinHeapSort(smallest);
}
}
void Heapify() {
for (int i = (data_.size() - 1) / 2; i >= 0; i--)
{
MinHeapSort(i);
}
}
public:
void Solve() {
ReadData();
Heapify();
WriteResponse();
}
};
int main() {
std::ios_base::sync_with_stdio(false);
HeapBuilder heap_builder;
heap_builder.Solve();
return 0;
}
Replaced if (right < data_.size() && data_[right] < data_[index]) with
if (right < data_.size() && data_[right] < data_[smallest])
That worked, silly mistake.

std::vector out of range for min-heap: C++

I've neglected to work on this code (or any other coding projects) for a while, so while I know what is basically wrong with the code, I've been having a hard time finding exactly where the vector is going out of range. I've been running gdb on it all morning to no avail. I'm trying to make a min-heap out of a vector "theData" in C++.
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
using std::swap;
using std::pair;
using std::make_pair;
class HeapBuilder {
private:
vector<int> data_;
vector< pair<int, int> > swaps_;
void WriteResponse() const {
cout << swaps_.size() << "\n";
for (int i = 0; i < swaps_.size(); ++i) {
cout << swaps_[i].first << " " << swaps_[i].second << "\n";
}
}
void ReadData() {
int n;
cin >> n;
data_.resize(n);
for(int i = 0; i < n; ++i)
cin >> data_[i];
}
void makeMinHeap(vector<int> &theData, int i, int n) {
int minIndex;
int left = 2*i;
int right = 2*i + 1;
if (left < n && theData.at(left) < theData.at(i)) {
minIndex = left;
}
else if (right < n && theData.at(right) < theData.at(i)) {
minIndex = right;
}
if (minIndex != i) {
swap(theData.at(i), theData.at(minIndex));
swaps_.push_back(make_pair(i, minIndex));
makeMinHeap(theData, minIndex, n);
}
}
void GenerateSwaps() {
swaps_.clear();
int size = data_.size();
for (int i = (size/2); i >= 0; i--) {
makeMinHeap(data_, i, size);
}
}
public:
void Solve() {
ReadData();
GenerateSwaps();
WriteResponse();
}
};
int main() {
std::ios_base::sync_with_stdio(false);
HeapBuilder heap_builder;
heap_builder.Solve();
return 0;
}
You are not putting in a check for minIndex.
Look what happens when your left<=n and right <=n both fails, most likely when the whole recursion is about to stop, since you just check
minIndex != i
// ^-- default each time is garbage which in case last>n && right>n leaves it garbage
// hence when it comes to
if(minIndex!=i){
// It's actually true where it was suppose to break out n thus throws out_of_range
}
Quick n easy solution would be to add a flagcheck
bool flagcheck = false;
if(){ flagcheck = true; }
else if(){ flagcheck = true; }
if(minIndex!=i && flagcheck){}

Program gives a weird runtime error

#include<iostream>
using namespace std;
class darray
{
private:
int n; // size of the array
int *a; // pointer to the 1st element
public:
darray(int size)
{
n = size;
a = new int[n];
}
~darray(){ delete[] a; }
void get_input();
int get_element(int index);
void set_element(int index, int value);
int count(){ return n; }
void print();
};
void darray::get_input()
{
for (int i = 0; i < n; i++)
{
cin >> *(a + i);
}
}
int darray::get_element(int index)
{
if (index == -1)
index = n - 1;
return a[index];
}
void darray::set_element(int index,int value)
{
a[index] = value;
}
void darray::print()
{
for (int i = 0; i < n; i++)
{
cout << a[i];
if (i < (n - 1))
cout << " ";
}
cout << endl;
}
// perform insertion sort on the array a
void insertion_sort(darray d)
{
int v = d.get_element(-1); // v is the right-most element
int e = d.count() - 1; // pos of the empty cell
// shift values greater than v to the empty cell
for (int i = (d.count() - 2); i >= 0; i--)
{
if (d.get_element(i) > v)
{
d.set_element(e,d.get_element(i));
d.print();
e = i;
}
else
{
d.set_element(e, v);
d.print();
break;
}
}
}
int main()
{
int s;
cin >> s;
darray d(s);
d.get_input();
insertion_sort(d);
system("pause");
return 0;
}
I use the darray class to make a array of size n at runtime. This class gives basic functions to handle this array.
This programs says debugging assertion failed at the end.
It gives this error after ruining the program.Other than that the program works fine. What is the reason for this error ?
You need to declare and define a copy constructor:
darray::darray(const darray& src)
{
n = src.n;
a = new int[n];
for (int i = 0; i < n; i++)
{
*(a + i) = *(src.a + i);
}
}

when i was using pointers in function arguments i faced with an error

The error is this:
cannot convert int*' toint*' for argument 1' tobool permition(int*, int, int)'
Here in code i have a int board[n], and the user gives the 'n'...
i want to give my permition function this array so i had to give it by pointers because the length of it is not specified...So how can i solve this problem
Here is my code:
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
bool permition(int* board[],int place,int n_){
int m=place;
while(m!=0){
m--;
if(abs(abs(board[m]-board[place])-abs(m-place))==1
&& abs(m-place)<3 && abs(board[m]-board[place]))
return false;
}
return true;
}
void printBoard(int* board[],int n){
for(int i=0;i<n;i++)
cout << board[i]<< " ";
cout << endl;
}
int main()
{
int p=0;
int n;
cout << "plz: ";
cin >> n;
int board[n];
for(int i=0;i<n;i++)
board[i]=0;
while(p<n){
while((board[p]<n) && permition(board,p,n)==false)
board[p]+=1;
if(board[p]<n)
p++;
else{
p--;
board[p]+=1;
}
if(p==n && board[0]<n-1)
//it means the first number is not max so we should
//print and continue from fist again
{
printBoard(board,n);
p=0;
board[0]+=1;
}
}
system("PAUSE");
return 0;
}
Get rid of [] in the function definition of permition:
bool permition(int* board,int place,int n_)
See if that helps!
Change
bool permition(int* board[],int place,int n_)
to
bool permition(int const board[],int place,int n_)
The current argument declaration (first above) says that board is an array of pointers to int, which it isn't.
The [] ends up as a pointer, so you can alternatively write
bool permition(int const* board,int place,int n_)
This form has the advantage that you can use const also on the pointer, while with [] you have a pointer that can be changed but that looks like an array.
The disadvantage is that the declaration no longer communicates "array" to the reader.
As others have noted, the original code passes an array of int (which is treated as an int *) to a function that's declared to take a pointer to an array of int. Here's a corrected version, with some formatting changes that I hope will be helpful.
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
// Removed unused parameter n_.
bool permission(int board[], int place) {
int m = place;
// The original code could return false only if (place - m) < 3,
// so no need to test when (place - m) >= 3.
while (m-- > max(0, place - 3) {
int board_diff = abs(board[m] - board[place];
int index_diff = place - m; // Always >= 0
if (abs(board_diff - index_diff) == 1 && board_diff != 0) {
return false;
}
}
return true;
}
void printBoard(int board[], int n) {
for (int i = 0; i < n; i++) {
cout << board[i] << " ";
}
cout << endl;
}
int main() {
int p = 0;
int n;
cout << "plz: ";
cin >> n;
int board[n] = { 0 }; // Zeroes entire array.
while (p < n) {
// Never compare bool to true or false; just use !bool_var.
while ((board[p] < n) && !permission(board, p)) {
board[p]++;
}
if (board[p] < n) {
p++;
} else {
board[--p]++;
}
if (p == n && board[0] < (n - 1)) {
// The first number is not max so we should
// print and continue from first again
printBoard(board, n);
board[p = 0]++; // Assign and increment.
}
}
system("PAUSE");
return 0;
}
int board[];
is the same as
int *board;
so the solution in my guess is to write that
bool permition(int board[],int place,int n_)
void printBoard(int board[],int n)
You need to understand and to work more on pointers !