Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<time.h>
- using namespace std;
- class MyDoubleStack
- {
- private:
- double * _array = NULL;
- int _arraySize = -1;
- int _arrayPos = -1;
- public:
- MyDoubleStack(int size)
- {
- _arraySize = size;
- _array = new double[_arraySize];
- for (int i = 0; i < _arraySize; i++) _array[i] = NAN;
- _arrayPos = -1;
- }
- ~MyDoubleStack()
- {
- delete[] _array;
- _array = NULL;
- _arraySize = -1;
- _arrayPos = -1;
- }
- void Push(double value)
- {
- if (!TryPush(value))
- {
- cout << "Can't push element. Maximum elements count reached." << endl;
- return;
- }
- }
- double Pop()
- {
- double res = NULL;
- if (!TryPop(&res))
- {
- cout << "Can't pop element. Stack is empty." << endl;
- return NAN;
- }
- return res;
- }
- bool TryPush(double value)
- {
- if (_arrayPos >= _arraySize-1) return false;
- _array[++_arrayPos] = value;
- return true;
- }
- bool TryPop(double * outValue)
- {
- if (_arrayPos <= -1) return false;
- *outValue = _array[_arrayPos];
- _array[_arrayPos] = NAN;
- _arrayPos--;
- return true;
- }
- };
- // http://stackoverflow.com/questions/2704521/generate-random-double-numbers-in-c
- double fRand(double fMin, double fMax)
- {
- double f = (double)rand() / RAND_MAX;
- return fMin + f * (fMax - fMin);
- }
- int main()
- {
- srand(time(0));
- int arrSize = 10;
- double ** arr = new double*[arrSize];
- cout << "Array of ptr to doubles:" << endl;
- for (int i = 0; i < arrSize; i++)
- {
- arr[i] = new double(fRand(-10, 10));
- cout << *arr[i] << endl;
- }
- cout << endl;
- MyDoubleStack positives(arrSize), negatives(arrSize);
- for (int i = 0; i < arrSize; i++)
- {
- if (*arr[i] < 0) negatives.Push(*arr[i]);
- else positives.Push(*arr[i]);
- }
- double d;
- cout << "Stack of positives was:" << endl;
- while (positives.TryPop(&d)) cout << d << endl;
- cout << endl;
- cout << "Stack of negatives was:" << endl;
- while (negatives.TryPop(&d)) cout << d << endl;
- cout << endl;
- for (int i = 0; i < arrSize; i++)
- {
- delete arr[i];
- }
- delete[] arr;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement