C++ Bin Packing Implementation using First Fit - c++

I'm doing a project for university but I encountered an exception which I don't understand. I'm using S.Sahni algorithms, so mostly I've got the code from his book. What I'm trying to do is to implement the Bin Packing problem with First Fit while I'm using tournament trees (max winner).
Here is my header:
// file winner.h
#ifndef WinnerTree_
#define WinnerTree_
#include <iostream>
#include <stdlib.h>
#include "xcept.h"
using namespace std;
template<class T>
class WinnerTree {
public:
WinnerTree(int TreeSize = 10);
~WinnerTree() {delete [] t;}
void Initialize(T a[], int size, int (&winner)(T a[], int player1, int player2));
int Winner()
{return (n) ? t[1] : 0;}
int Winner(int i)
{return (i < n) ? t[i] : 0;}
void RePlay(int i, int (&winner)(T a[], int player1, int player2));
void Output();
private:
int MaxSize;
int n; // current size
int LowExt; // lowest-level external nodes
int offset; // 2^k - 1
int *t; // array for winner tree
T *e; // element array
void Play(int p, int lc, int rc, int (&winner)(T a[], int player1, int player2));
};
template<class T>
WinnerTree<T>::WinnerTree(int TreeSize)
{// Constructor for winner tree.
MaxSize = TreeSize;
t = new int[MaxSize];
n = 0;
}
template<class T>
void WinnerTree<T>::Initialize(T a[], int size, int (&winner)(T a[], int player1, int player2))
{// Initialize winner t for array a.
if (size > MaxSize || size < 2)
throw BadInput();
n = size;
e = a;
// compute s = 2^log (n-1)
int i, s;
for (s = 1; 2*s <= n-1; s += s);
LowExt = 2*(n-s);
offset = 2*s-1;
// play matches for lowest-level external nodes
for (i = 2; i <= LowExt; i += 2)
Play((offset+i)/2, i-1, i, winner);
// handle remaining external nodes
if (n % 2) {// special case for odd n, play
// internal and external node
Play(n/2, t[n-1], LowExt+1, winner);
i = LowExt+3;}
else
i = LowExt+2;
// i is left-most remaining external node
for (; i <= n; i += 2)
Play((i-LowExt+n-1)/2, i-1, i, winner);
}
template<class T>
void WinnerTree<T>::Play(int p, int lc, int rc, int (&winner)(T a[], int player1, int player2))
{// Play matches beginning at t[p].
// lc and rc are the children of t[p].
t[p] = winner(e, lc, rc);
// more matches possible if at right child
while (p > 1 && p % 2) {// at a right child
t[p/2] = winner(e, t[p-1], t[p]);
p /= 2; // go to parent
}
}
template<class T>
void WinnerTree<T>::RePlay(int i, int(&winner)(T a[], int player1, int player2))
{// Replay matches for element i.
if (i <= 0 || i > n)
throw OutOfBounds();
int p, // match node
lc, // left child of p
rc; // right child of p
// find first match node and its children
if (i <= LowExt) {// begin at lowest level
p = (offset + i)/2;
lc = 2*p - offset; // left child of p
rc = lc+1;}
else {
p = (i-LowExt+n-1)/2;
if (2*p == n-1) {
lc = t[2*p];
rc = i;}
else {
lc = 2*p - n + 1 + LowExt;
rc = lc+1;}
}
t[p] = winner(e, lc, rc);
// play remaining matches
p /= 2; // move to parent
for (; p >= 1; p /= 2)
t[p] = winner(e, t[2*p], t[2*p+1]);
}
template<class T>
void WinnerTree<T>::Output()
{
cout << "size = "<< n << " LowExt = " << LowExt
<< " Offset = " << offset << endl;
cout << "Winner tree pointers are" << endl;
for (int i = 1; i < n; i++)
cout << t[i] << ' ';
cout << endl;
}
#endif
This is my exception file:
#ifndef Xcept_
#define Xcept_
#include <exception>
#include <new.h>
// bad initializers
class BadInitializers {
public:
BadInitializers() {}
};
// insufficient memory
class NoMem {
public:
NoMem() {}
};
// change new to throw NoMem instead of xalloc
void my_new_handler()
{
throw NoMem();
};
new_handler Old_Handler_ = set_new_handler(my_new_handler);
// improper array, find, insert, or delete index
// or deletion from empty structure
class OutOfBounds {
public:
OutOfBounds() {}
};
// use when operands should have matching size
class SizeMismatch {
public:
SizeMismatch() {}
};
// use when zero was expected
class MustBeZero {
public:
MustBeZero() {}
};
// use when zero was expected
class BadInput {
public:
BadInput() {}
};
#endif
And this is my main function:
// First fit bin packing
#include "stdafx.h"
using namespace std;
#include <iostream>
#include "winner.h"
int winner(int a[], int player1, int player2)
{// For a max winner tree.
if (a[player1] >= a[player2])
return player1;
return player2;
}
void FirstFitPack(int s[], int n, int c)
{// Output first fit packing into bins of size c.
// n is the number of objects and s[] their size.
WinnerTree<int> *W = new WinnerTree<int>(n);
int *avail = new int[n + 1]; // bins
// initialize n bins and winner tree
for (int i = 1; i <= n; i++)
avail[i] = c; // initial available capacity
W->Initialize(avail, n, winner);
// put objects in bins
for (int i = 1; i <= n; i++) {// put s[i] in a bin
// find first bin with enough capacity
int p = 2; // start search at left child of root
while (p < n) {
int winp = W->Winner(p);
if (avail[winp] < s[i]) // first bin is in
p++; // right subtree
p *= 2; // move to left child
}
int b; // will be set to bin to use
p /= 2; // undo last left child move
if (p < n) {// at a tree node
b = W->Winner(p);
// if b is right child, need to check
// bin b-1. No harm done by checking
// bin b-1 even if b is left child.
if (b > 1 && avail[b - 1] >= s[i])
b--;
}
else // arises when n is odd
b = W->Winner(p / 2);
cout << "Pack object " << i << " in bin "
<< b << endl;
avail[b] -= s[i]; // update avail. capacity
W->RePlay(b, winner);
getchar();
}
}
int main(void)
{
int n, c; // number of objects and bin capacity
cout << "Enter number of objects" << endl;
cin >> n;
if (n < 2) {
cout << "Too few objects" << endl;
exit(1);
}
cout << "Enter bin capacity" << endl;
cin >> c;
int *s = new int[n + 1];
for (int i = 1; i <= n; i++) {
cout << "Enter space requirement of object " << i << endl;
cin >> s[i];
if (s[i] > c) {
cout << "Object too large to fit in a bin" << endl;
exit(1);
}
}
FirstFitPack(s, n, c);
return 0;
}
The exception that I get is:
First-chance exception at 0x0012668D in Bin Packing-FF.exe: 0xC0000005: Access violation reading location 0xF9039464.
I know that I'm getting this exception because of the winner. But I can't understand what I have to change here.
int winner(int a[], int player1, int player2)
{// For a max winner tree.
if (a[player1] >= a[player2])
return player1;
return player2;
}
Also, If I press space or enter after the last input (object) then I don't get the exception and everything is going smoothly. But still I want to know why I'm getting this exception.
Thank you in advance.

Related

Calling function from one class in another in C++

So, I am writing a program in C++ that has a function in the Sort class that I wish to call in the Main class. The function has several data members used that are present in that class, that are not present in the Main class and I keep getting a C2660 error, that "Function does not take 0 arguments". Is there a way (short of writing a bunch of getters and setters) to resolve this?
#include "Sort.h"
#include "Timer.h"
using namespace std;
int main
{
Sort *sort = new Sort();
Timer ti;
sort->SetRandomSeed(12345);
sort->InitArray();
cout << "starting InsertionSort" << endl;
ti.Start();
sort->InsertionSort();
ti.End();
cout << "Insertion sort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
//sort->InitList();
//cout << "starting InsertionSortList()" << endl;
//ti.Start();
//sort->InsertionSortList();
//ti.End();
//cout << "Insertion sort list duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting SelectionSort" << endl;
ti.Start();
sort->SelectionSort();
ti.End();
cout << "SelectionSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting MergeSort" << endl;
ti.Start();
sort->MergeSort();
ti.End();
cout << "MergeSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting QuickSort" << endl;
ti.Start();
sort->QuickSort();
ti.End();
cout << "QuickSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitVector();
cout << "starting std::sort() of Vector<int>" << endl;
ti.Start();
sort->VectorSort();
ti.End();
cout << "std::sort() duration: " << ti.DurationInNanoSeconds() << "ns" << endl;
delete sort;
cout << endl <<"Press [Enter] key to exit";
getchar();
}
Sort.cpp
//const int for array
int num = 10000000;
int val = 10000;
//array
int *tmpArray, *qArr, *insArr, *selArr, *mergArr = NULL;
int low, high;
//duration for timer
int duration = 0;
Sort::Sort()
{
}
Sort::~Sort()
{
}
void Sort::InitArray()
{
//int for index
int i = 0;
tmpArray = new int[num];
qArr = new int[num];
insArr = new int[num];
selArr = new int[num];
mergArr = new int[num];
//fill temp array with sequential numbers
for (int i = 0; i < num; i++)
{
tmpArray[i] = 1 + rand() % val;
}
for (i = 0; i < num; i++)
{
qArr[i] = tmpArray[i];
insArr[i] = tmpArray[i];
selArr[i] = tmpArray[i];
mergArr[i] = tmpArray[i];
}
low = qArr[0];
high = qArr[num - 1];
int n = sizeof(tmpArray) / sizeof(tmpArray[0]);
}
void Sort::InitVector()
{
vector<int> v(num);
std::generate(v.begin(), v.end(), std::rand);
}
void Sort::InitList()
{
// A set to store values
std::list<int> l;
// Loop until we get 50 unique random values
while (l.size() < num)
{
l.push_back(1 + rand() % val);
}
for (int n : l) {
std::cout << n << '\n';
}
}
//setting seed
void Sort::SetRandomSeed(unsigned int seed)
{
seed = rand();
}
void Sort::InsertionSort()
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = insArr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && insArr[j] > key)
{
insArr[j + 1] = insArr[j];
j = j - 1;
}
insArr[j + 1] = key;
}
delete[] insArr;
insArr = NULL;
}
int Sort::partition(int qArr[], int low, int high)
{
int pivot = qArr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (qArr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&qArr[i], &qArr[j]);
}
}
swap(&qArr[i + 1], &qArr[high]);
return (i + 1);
}
void Sort::QuickSort(int qArr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(qArr, low, high);
// Separately sort elements before
// partition and after partition
QuickSort(qArr, low, pi - 1);
QuickSort(qArr, pi + 1, high);
}
delete[] qArr;
qArr = NULL;
}
void Sort::SelectionSort()
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++)
if (selArr[j] < selArr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&selArr[min_idx], &selArr[i]);
}
delete[] selArr;
selArr = NULL;
}
void Sort::swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void Sort::VectorSort()
{
std::sort(v.begin(), v.end());
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void Sort::merge(int mergArr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int* L;
int* R;
/* create temp arrays */
L = new int[n1];
R = new int[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = mergArr[l + i];
for (j = 0; j < n2; j++)
R[j] = mergArr[m + 1 + j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
mergArr[k] = L[i];
i++;
}
else
{
mergArr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
mergArr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
mergArr[k] = R[j];
j++;
k++;
}
}
void Sort::MergeSort(int mergArr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
MergeSort(mergArr, l, m);
MergeSort(mergArr, m + 1, r);
merge(mergArr, l, m, r);
}
delete[] mergArr;
mergArr = NULL;
}
Sort.h
#include <iomanip>
#include <fstream>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#include<list>
using namespace std;
#pragma once
class Sort
{
public:
Sort();
~Sort();
void InitArray();
void InitVector();
void InitList();
void SetRandomSeed(unsigned int seed);
int n, right, left, l, r, m;
vector<int> v;
void InsertionSort();
int partition(int qArr[], int low, int high);
void QuickSort(int qArr[], int low, int high);
void swap(int * xp, int * yp);
void VectorSort();
void MergeSort(int arr[], int l, int r);
void merge(int arr[], int l, int m, int r);
void SelectionSort();
};
Ignoring the Timer class (those are all good) here is the rest of the code. The C2660 errors are shown for the sort->MergeSort() and sort->QuickSort() calls in main.
I resolved the issues myself. I created helper functions in the Sort class that have no arguments and call the functions themselves to use in the main. Helper Functions shown below.
Sort.cpp
//method for Main to run to prevent C2660 errors
void Sort::mergeHelper()
{
MergeSort(mergArr, l, r);//call merge sort method
}
//method for Main to run to prevent C2660 errors
void Sort::quickHelper()
{
QuickSort(qArr, low, high);//call quick sort method
}
int Main
{
sort->quickHelper();
sort->mergeHelper();
}

Converting Decimal Number to Binary Number using stack

I am trying to convert a decimal number to binary number using stacks and I have to use structs.
Now from my understanding of structs, we can have member functions in them. And stack follows a LIFO strategy.
We can create a stack by making a struct, declaring some members, and have some functions to initialize and work on these members.
So, I tried declaring a struct with above mentioned things and my understanding, but I still do not seem to get the concept right. I believe it is an error on my part. But reading forums still does not help as we have not been taught classes yet and on every forum, structs and classes are intermixed.
Here is my code so far, any help and guidance regarding the concept and logic would be much appreciated.
#include<iostream>
using namespace std;
struct bin{
int num[15];
int ci;
void init()
{
ci = 0;
for (int i = 0;i < 15;i++)
num[i] = -1;
}
void push(int n)
{
num[ci] = n;
ci++;
}
int pop()
{
int temp = num[--ci];
num[ci] = -1;
return temp;
}
};
int main()
{
int inp, count = 0;
bin var;
cout << "Enter a decimal number to convert into binary: ";
cin >> inp;
while (inp != 0)
{
int rem = inp % 2;
cout << "rem= " << rem << endl;
inp /= 2;
cout << "inp= " << inp << endl;
var.push(rem);
count++;
}
cout << "\nYour binary is: ";
while (count != 0)
{
cout << var.pop();
count--;
}
return 0;
}
I tried my best to find the mistakes but couldn't. So,in the end I simply used arrays and implemented the code as follows
#include<iostream>
using namespace std;
void push(int bin[], int n, int &ci);
void init(int bin[], int &count, int &ci);
int pop(int bin[], int &ci);
void display(int bin[], int &count, int &ci);
void findBinary(int bin[], int &count, int&ci, int &inp);
int main()
{
int inp, count, ci;
int bin[20];
char c = '\0';
init(bin,count,ci);
cout << "Enter a decimal number to convert into binary: ";
cin >> inp;
findBinary(bin, count, ci, inp);
display(bin, count, ci);
return 0;
}
void init(int bin[], int &count, int &ci)
{
count = 0;
ci = 0;
for (int i = 0;i < 20;i++)
bin[i] = -1;
}
int pop(int bin[], int &ci)
{
int temp = bin[--ci];
return temp;
}
void push(int bin[], int n, int &ci)
{
bin[ci] = n;
ci++;
}
void display(int bin[], int &count, int &ci)
{
cout << "\nYour binary is: ";
while (count != 0)
{
cout << pop(bin, ci);
count--;
}
cout << endl;
}
void findBinary(int bin[], int &count, int&ci, int &inp)
{
while (inp != 0)
{
int rem = inp % 2;
inp /= 2;
push(bin, rem, ci);
count++;
}
}
So my questions are:
1. When we write a function within a struct, does the function runs when we create a struct type object?
2. Is the method I used to implement stack using struct in the first example correct?
When you first create an object from a struct or class, the constructor runs - but no other function (so not your init function). If you want that to run, you need to call it explicitly:
bin var;
var.init();
In terms of the implementation of your functions: you should use bounds-checking to ensure that you don't push more items than you can handle, or pop more than are in the queue. Besides that I can't see much wrong with them. Consider using a std::vector instead of an array, but as you're just starting to learn about C++, you'll likely cover that later in your course.
By the time you're adding constructors to a struct though, you may as well switch to using a class. In C++, structs and classes are equivalent (with the minor tweak that the default access modifier in a struct is public, whereas in classes it's private), so don't let that put you off.
why don't you do the problem in this way ,I fixed it just like this .
#include
using namespace std;
#define MAX_STACK 10
int top=-1;
struct bin
{
int num[MAX_STACK];
bool isEmpty()
{
return (top < 0);
}
void push(int newItem)
{
// if stack has no more room for
// another item
if (top >= MAX_STACK-1)
cout<<"Stack Overflow!";
else{
++top;
num[top] = newItem;
}
}
int pop()
{
if(top < 0)
{
//top points to nothing i.e stack is empty
cout << "Stack Underflow \n";
return 0;
}
else
{
/*decrement the top pointer and it
points to the next top element in the stack*/
int d = num[top--];
return d;
}
}
};
int main()
{
int value, count = 0;
bin var;
int rem;
cout << "Enter a decimal number to convert into binary: ";
cin >> value;
while (value != 0)
{
rem = value % 2;
cout << "rem= " << rem << endl;
var.push(rem);
count++;
value /= 2;
}
cout << "\nYour binary is: ";
while (count != 0)
{
cout << var.pop();
count--;
}
return 0;
}

Can't understand why my program throws error

My code is in
#include <iostream>
#include <string>
#include <algorithm>
#include <climits>
#include <vector>
#include <cmath>
using namespace std;
struct State {
int v;
const State *rest;
void dump() const {
if(rest) {
cout << ' ' << v;
rest->dump();
} else {
cout << endl;
}
}
State() : v(0), rest(0) {}
State(int _v, const State &_rest) : v(_v), rest(&_rest) {}
};
void ss(int *ip, int *end, int target, const State &state) {
if(target < 0) return; // assuming we don't allow any negatives
if(ip==end && target==0) {
state.dump();
return;
}
if(ip==end)
return;
{ // without the first one
ss(ip+1, end, target, state);
}
{ // with the first one
int first = *ip;
ss(ip+1, end, target-first, State(first, state));
}
}
vector<int> get_primes(int N) {
int size = floor(0.5 * (N - 3)) + 1;
vector<int> primes;
primes.push_back(2);
vector<bool> is_prime(size, true);
for(long i = 0; i < size; ++i) {
if(is_prime[i]) {
int p = (i << 1) + 3;
primes.push_back(p);
// sieving from p^2, whose index is 2i^2 + 6i + 3
for (long j = ((i * i) << 1) + 6 * i + 3; j < size; j += p) {
is_prime[j] = false;
}
}
}
}
int main() {
int N;
cin >> N;
vector<int> primes = get_primes(N);
int a[primes.size()];
for (int i = 0; i < primes.size(); ++i) {
a[i] = primes[i];
}
int * start = &a[0];
int * end = start + sizeof(a) / sizeof(a[0]);
ss(start, end, N, State());
}
It takes one input N (int), and gets the vector of all prime numbers smaller than N.
Then, it finds the number of unique sets from the vector that adds up to N.
The get_primes(N) works, but the other one doesn't.
I borrowed the other code from
How to find all matching numbers, that sums to 'N' in a given array
Please help me.. I just want the number of unique sets.
You've forgotten to return primes; at the end of your get_primes() function.
I'm guessing the problem is:
vector<int> get_primes(int N) {
// ...
return primes; // missing this line
}
As-is, you're just writing some junk here:
vector<int> primes = get_primes(N);
it's undefined behavior - which in this case manifests itself as crashing.

C++ strange class declaration

I'm practicing ACM problems to become a better programmer, but I'm still fairly new to c++ and I'm having trouble interpreting some of the judges code I'm reading. The beginning of a class starts with
public:
State(int n) : _n(n), _p(2*n+1)
{
and then later it's initialized with
State s(n);
s(0,0) = 1;
I'm trying to read the code but I can't make sense of that. The State class only seems to have 1 argument passed, but the programmer is passing 2 in his initialization. Also, what exactly is being set = to 1? As far as I can tell, the = operator isn't being overloaded but just in case I missed something I've included the full code below.
Any help would be greatly appreciated.
Thanks in advance
/*
* D - Maximum Random Walk solution
* ICPC 2012 Greater NY Regional
* Solution by Adam Florence
* Problem by Adam Florence
*/
#include <cstdio> // for printf
#include <cstdlib> // for exit
#include <algorithm> // for max
#include <iostream>
#include <vector>
using namespace std;
class State
{
public:
State(int n) : _n(n), _p(2*n+1)
{
if (n < 1)
{
cout << "Ctor error, n = " << n << endl;
exit(1);
}
for (int i = -n; i <= n; ++i)
_p.at(i+_n) = vector<double>(n+1, 0.0);
}
void zero(const int n)
{
for (int i = -n; i < n; ++i)
for (int m = 0; m <= n; ++m)
_p[i+_n][m] = 0;
}
double operator()(int i, int m) const
{
#ifdef DEBUG
if ((i < -_n) || (i > _n))
{
cout << "Out of range error, i = " << i << ", n = " << _n << endl;
exit(1);
}
if ((m < 0) || (m > _n))
{
cout << "Out of range error, m = " << m << ", n = " << _n << endl;
exit(1);
}
#endif
return _p[i+_n][m];
}
double& operator()(int i, int m)
{
#ifdef DEBUG
if ((i < -_n) || (i > _n))
{
cout << "Out of range error, i = " << i << ", n = " << _n << endl;
exit(1);
}
if ((m < 0) || (m > _n))
{
cout << "Out of range error, m = " << m << ", n = " << _n << endl;
exit(1);
}
#endif
return _p[i+_n][m];
}
static int min(int x, int y)
{
return(x < y ? x : y);
}
static int max(int x, int y)
{
return(x > y ? x : y);
}
private:
int _n;
// First index is the current position, from -n to n.
// Second index is the maximum position so far, from 0 to n.
// Value is probability.
vector< vector<double> > _p;
};
void go(int ds)
{
// Read n, l, r
int n, nds;
double l, r;
cin >> nds >> n >> l >> r;
const double c = 1 - l - r;
if(nds != ds){
cout << "Dataset number " << nds << " does not match " << ds << endl;
return;
}
// Initialize state, probability 1 at (0,0)
State s(n);
s(0,0) = 1;
State t(n);
State* p1 = &s;
State* p2 = &t;
for (int k = 1; k <= n; ++k)
{
// Compute probabilities at step k
p2->zero(k);
// At step k, the farthest from the origin you can be is k
for (int i = -k; i <= k; ++i)
{
const int mm = State::min( State::max(0, i+k), k);
for (int m = 0; m <= mm; ++m)
{
// At step k-1, p = probability of (i,m)
const double p = p1->operator()(i,m);
if (p > 0)
{
// Step left
p2->operator()(i-1, m) += p*l;
// Step right
p2->operator()(i+1, State::max(i+1,m)) += p*r;
// Stay put
p2->operator()(i, m) += p*c;
}
}
}
swap(p1, p2);
}
// Compute expected maximum position
double p = 0;
for (int i = -n; i <= n; ++i)
for (int m = 0; m <= n; ++m)
p += m * p1->operator()(i,m);
printf("%d %0.4f\n", ds, p);
}
int main(int argc, char* argv[])
{
// Read number of data sets to process
int num;
cin >> num;
// Process each data set identically
for (int i = 1; i <= num; ++i)
go(i);
// We're done
return 0;
}
You are confusing a call to state::operator()(int, int) with an initialization. That operator call lets you set the value of an element of the class instance.
State s(n); // this is the only initialization
s(0,0) = 1; // this calls operator()(int, int) on instance s
In this line:
s(0,0) = 1;
it's calling this:
double& operator()(int i, int m)
and because it returns a reference to a double, you can assign to it.
The second line is no longer initialization. The constructor was invoked in line 1, the second line invokes
double& operator()(int i, int m)
with n=0 and m=0 and writing 1 to the reference that is returned.
This part:
State(int n) : _n(n), _p(2*n+1)
...is a member initializer list. It's sort of similar to if you'd written the construct like:
state(int n) { _n = n; _p = 2*n+1; }
...except that it initializes _n and _p instead of starting with them unitialized, then assigning values to them. In this specific case that may not make much difference, but when you have things like references that can only be initialized (not assigned) it becomes crucial.
The s(0,0) = 1 looks like s is intended to act a little like a 2D array, and they've overloaded operator() to act as a subscripting operator for that array. I posted a class that does that in a previous answer.

FirstChance Exception StackOverFlow Merge Sort Shell Sort Bubble Sort

Hey guys I'm working on some sorts and am trying to implement a bubble sort, a merge sort, and a shell sort. I use an outdated technique but I was wondering if you guys could let me know why I keep getting the following error:
First-chance exception at 0x01135EF7 in sortApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00542000).
Unhandled exception at 0x01135EF7 in sortApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00542000).
I am using Visual Studio 2012 if that plays any part. My code is in three different files so I'll post each separately.
My header file:
#pragma once
class sort
{
public:
sort();
void random1(int array[]);
void random2(int array[]);
void random3(int array[]);
void bubbleSort(int array[], int length);
/*void merge(int *input, int p, int r);
void merge_sort(int *input, int p, int r);*/
void shellSort(int array[], int length);
};
My class implementation file:
#include "sort.h"
#include <time.h>
#include <iostream>
using namespace std;
sort::sort()
{}
void sort::random1(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 25; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::random2(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 10000; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::random3(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 100000; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::bubbleSort(int array[], int length)
{
//Bubble sort function
int i,j;
for(i = 0; i < 10; i++)
{
for(j = 0; j < i; j++)
{
if(array[i] > array[j])
{
int temp = array[i]; //swap
array[i] = array[j];
array[j] = temp;
}
}
}
}
/*void sort::merge(int* input, int p, int r) //the merge algorithm of the merge sort
{
int mid = (p + r) / 2;
int i1 = 0;
int i2 = p;
int i3 = mid + 1;
// Temp array
int x = r -p + 1;
int *temp;
temp = new int [x];
// Merge in sorted form the 2 arrays
while ( i2 <= mid && i3 <= r )
if ( input[i2] < input[i3] )
temp[i1++] = input[i2++];
else
temp[i1++] = input[i3++];
// Merge the remaining elements in left array
while ( i2 <= mid )
temp[i1++] = input[i2++];
// Merge the remaining elements in right array
while ( i3 <= r )
temp[i1++] = input[i3++];
// Move from temp array to master array
for ( int i = p; i <= r; i++ )
input[i] = temp[i-p];
}
void sort::merge_sort(int *input, int p, int r) //the merge sort algorithm
{
if ( p < r ) //When p and r are equal the recursion stops and the arrays are then passed to the merge function.
{
int mid = (p + r) / 2;
merge_sort(input, p, mid); //recursively calling the sort function in order to break the arrays down as far as possible
merge_sort(input, mid + 1, r);//recursively calling the sort function in order to break the arrays down as far as possible
merge(input, p, r); //merge function realigns the smaller arrays into bigger arrays until they are all one array again
}
}*/
void sort::shellSort(int array[], int length) //Shell sort algorithm
{
int gap, i, j, temp;
for( gap = length / 2; gap > 0; gap /= 2) //gap is the number of variables to skip when doing the comparisons
{
for( i = gap; i < length; i++) //This for loop sets the variable to use as the gap for the comparisons
{
for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j -= gap)
{
temp = array[j]; //the array variables are swapped
array[j] = array[j + gap];
array[j + gap] = temp;
}
}
}
}
And my driver file:
#include "sort.h"
#include <iostream>
using namespace std;
int main()
{
int bubbleArray1[25]; //these are the arrays to be sorted. three for each sort. each has a length of 25, 10000, or 100000.
int bubbleArray2[10000];
int bubbleArray3[100000];
int mergeArray1[25];
int mergeArray2[10000];
int mergeArray3[100000];
int shellArray1[25];
int shellArray2[10000];
int shellArray3[100000];
sort Sorts;
Sorts.random1(bubbleArray1);
Sorts.random1(mergeArray1);
Sorts.random1(shellArray1);
Sorts.random2(bubbleArray2);
Sorts.random2(mergeArray2);
Sorts.random2(shellArray2);
Sorts.random3(bubbleArray3);
Sorts.random3(mergeArray3);
Sorts.random3(shellArray3);
cout << "BubbleSort1 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray1, 25);
cout << "BubbleSort2 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray2, 10000);
cout << "BubbleSort3 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray3, 100000);
cout << "End bubble sorts.\n";
/*cout << "MergeSort1 is now being sorted.\n";
Sorts.merge_sort(mergeArray1, 0, 25);
cout << "MergeSort2 is now being sorted.\n";
Sorts.merge_sort(mergeArray2, 0, 10000);
cout << "MergeSort3 is now being sorted.\n";
Sorts.merge_sort(mergeArray3, 0, 100000);
cout << "End merge sorts.\n";*/
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray1, 25);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray2, 10000);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray3, 100000);
cout << "End shell sorts.\n";
cout << "Array\tElements\n";
cout << "BubbleSort1\t";
for(int i = 0; i < 25; i++)
{
cout << bubbleArray1[i] << " ";
}
cout << "\nMergeArray1\t";
for(int i = 0; i < 25; i++)
{
cout << mergeArray1[i] << " ";
}
cout << "\nShellArray1\t";
for(int i = 0; i < 25; i++)
{
cout << shellArray1[i] << " ";
}
return 0;
}
I know it's a lot of code. And there are probably many ways I could make the code better.
I would just like to know what's causing the error up above since I can't find it using my compiler.
You are allocating too much memory on the stack. Variables with 'automatic' storage class go on the stack. Allocate heap instead.
So, instead of:
int shellArray3[100000];
Do:
int* shellArray3 = new int[100000];
Or better yet, use std::vector.
If you don't want to use heap memory, you could also use the static storage class for something like this. To do that:
static int shellArray3[100000];
That will allocate one instance of the variable for the whole program rather than allocating a copy for each function entry on the stack.