c++ Class not working - c++

I'm working on a simple timer class and I don't know what the problem is.
I tried a few ways but I can't figure it out.
I know this question has already been asked, but can someone help me?
class timer
{
int interval;
int count;
bool run;
public:
//constructor
timer(int interval);
~timer()
{
}
;
void start();
void setInterval(int intv);
void pause();
};
timer::timer(int intval)
{
interval = intval;
}
void timer::start()
{
run = true;
while (run)
{
count++;
if (count < interval)
{
}
else
{
//reset timer interval
count = 0;
cout << "sdsds";
}
}
}
void timer::pause()
{
run = false;
}
void timer::setInterval(int intv)
{
interval = intv;
}

I would say that this
timer::timer(int intval)
{
interval = intval;
}
should be this
timer::timer(int intval)
{
interval = intval;
count = 0;
}
As far as I can see you aren't initialising count.

Related

why i got assertion failure, vector subscipt out of range

Visual studio said I got no issue but, every time I try to run my code I get an assertion failure error, and the error says that vector subscript is out of range, what should I do to fix this, I dont really know what I am doing wrong.
#include <iostream>
#include <ctime>
#include <windows.h>
#include <conio.h>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
class Human
{
private:
int ap;
int hp;
public:
Human()
{
srand(time(NULL));
ap = rand() % 3 + 8;
hp = rand() % 2 + 9;
}
int getAp() { return ap; }
int getHp() { return hp; }
void dmg(int x) { hp -= x; }
};
class Skeleton
{
private:
int ap;
int hp;
public:
Skeleton()
{
srand(time(NULL));
ap = rand() % 3 + 3;
hp = rand() % 2 + 4;
}
int getAp() { return ap; }
int getHp() { return hp; }
void dmg(int x) { hp -= x; }
};
class game
{
private:
std::vector<Human*> hum;
std::vector<Skeleton*> ske;
bool adv;
int sC;
int hC;
public:
game(int h, int s)
{
srand(time(NULL));
adv = rand() % 2;
sC = s;
hC = h;
for (int i = 0; i < h; i++) { hum.push_back( new Human()); }
for (int i = 0; i < h; i++) { ske.push_back(new Skeleton()); }
}
~game()
{
for (int i = 0; i < hum.size(); i++)
{
Human* current = hum.back();
hum.pop_back();
delete current;
}
for (int i = 0; i < ske.size(); i++)
{
Skeleton* current = ske.back();
ske.pop_back();
delete current;
}
}
void start()
{
int x = hC-1;
int y = sC-1;
bool quit = false;
while (!quit)
{
if (adv)
{
ske[y]->dmg(hum[x]->getAp());
if (ske[y]->getHp() <= 0) { y--; ske.pop_back();}
adv = 0;
}
if (!adv)
{
hum[x]->dmg(ske[y]->getAp());
if (hum[x]->getHp() <= 0) { x--; hum.pop_back(); }
adv = 1;
}
if (hum.size() == 0 || ske.size() == 0)
{
cout << "human left : " << hum.size() << "skeleton left : " << ske.size();
quit = true;
}
}
}
};
int main()
{
game g1(10, 5);
g1.start();
return 0;
}
I always get this error box.
this is the error message i got no idea what are they talkin about.
I also get this, what is this?
this
ive fixed it thx to all of ur comments,
this is the completed code, it may look like garbage but it runs
#include <iostream>
#include <ctime>
#include <windows.h>
#include <conio.h>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
class Human
{
private:
int ap;
int hp;
public:
Human()
{
ap = rand() % 3 + 8;
hp = rand() % 2 + 9;
}
int getAp() { return ap; }
int getHp() { return hp; }
void dmg(int x) { hp -= x; }
};
class Skeleton
{
private:
int ap;
int hp;
public:
Skeleton()
{
ap = rand() % 3 + 3;
hp = rand() % 2 + 4;
}
int getAp() { return ap; }
int getHp() { return hp; }
void dmg(int x) { hp -= x; }
};
class game
{
private:
std::vector<Human*> hum;
std::vector<Skeleton*> ske;
bool adv;
int sC;
int hC;
public:
game(int h, int s)
{
srand(time(NULL));
adv = rand() % 2;
sC = s;
hC = h;
for (int i = 0; i < h; i++) { hum.push_back( new Human()); }
for (int i = 0; i < s; i++) { ske.push_back(new Skeleton()); }
}
~game()
{
for (int i = 0; i < hum.size(); i++)
{
Human* current = hum.back();
hum.pop_back();
delete current;
}
for (int i = 0; i < ske.size(); i++)
{
Skeleton* current = ske.back();
ske.pop_back();
delete current;
}
}
void start()
{
int x = hum.size()-1;
int y = ske.size()-1;
bool quit = false;
while (!quit)
{
if (hum.size() == 0 || ske.size() == 0)
{
cout << "human left : " << hum.size() << "skeleton left : " << ske.size();
quit = true;
break;
}
if (adv)
{
ske.at(y)->dmg(hum.at(x)->getAp());
if (ske.at(y)->getHp() <= 0) { y--; ske.pop_back();}
adv = 0;
}
else if (!adv)
{
hum.at(x)->dmg(ske.at(y)->getAp());
if (hum.at(x)->getHp() <= 0) { x--; hum.pop_back(); }
adv = 1;
}
}
}
};
int main()
{
game g1(8, 20);
g1.start();
return 0;
}
Your final code is somewhat complex than it should be, I have simplified it by:
Remove the windows related header files, they are not used
Use member initializer lists
Modify dmg to return the latest hp
Remove the unnecessary index in start, to use back
Remove the vector of pointers, it's Ok to use objects here
Move the srand call into main(Actually we can use std::random here)
Simplify the while loop in start
#include <ctime>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
class Human {
private:
int ap;
int hp;
public:
Human() : ap(rand() % 3 + 8), hp(rand() % 2 + 9) {}
int getAp() { return ap; }
int getHp() { return hp; }
int dmg(int x) { return hp -= x; }
};
class Skeleton {
private:
int ap;
int hp;
public:
Skeleton() : ap(rand() % 3 + 3), hp(rand() % 2 + 4) {}
int getAp() { return ap; }
int getHp() { return hp; }
int dmg(int x) { return hp -= x; }
};
class game {
private:
bool adv;
int sC;
int hC;
std::vector<Human> hum;
std::vector<Skeleton> ske;
public:
game(int h, int s) : adv(rand() % 2), sC(s), hC(h), hum(h), ske(s) {}
void start() {
while (!hum.empty() && !ske.empty()) {
if (adv) {
if (ske.back().dmg(hum.back().getAp()) <= 0) {
ske.pop_back();
}
} else {
if (hum.back().dmg(ske.back().getAp()) <= 0) {
hum.pop_back();
}
}
adv = !adv;
}
cout << "human left : " << hum.size() << ", skeleton left : " << ske.size();
}
};
int main() {
srand(time(NULL));
game g1(8, 20);
g1.start();
return 0;
}
Online demo
In function start, ske[y] is accessed with a negative index. std::vector does not like negative indexes, this needs to be fixed.

C++ program on single serving queing

I am a noobie with C++, and have only basic knowledge. I am trying to make a program for my 'operation research' class. I have written a code that works like a flowchart for a single server queuing system. I am getting multiple errors (which seem simple) but cant figure out how to fix them (being a noobie). Some examples are 'missing terminating character', 'stray', and 'not declared in this scope'. All help is much appreciated.
#include <iostream>
#include <cmath>
using namespace std;
const int BUSY=1;
const int IDLE=0;
int
choice,
WL,
SS;
double
MX,
IT,
ST,
TM,
AT,
DT,
TypeOfEvent,
NextServiceTime,
ProgressAT’
ProgressDT;
void initialize();
void Timing();
void Arrival();
void Departure();
float expon(float mean);
int main()
{
initialize();
do
{
cout<<"Enter your Policy: ";
cin>>choice;
}
while(choice>2||choice<1);
cout<<"'End of Simulation’ Time: "<<MX<<endll;
while(true)
{ Timing(); //To Determine The Next Event
if(TM>MX)
break;
switch (int(TypeOfEvent))
{ case 1:
Arrival();
break;
case 2:
Departure();
break;
}
}
return 0;
}
void initialize()
{ IT=1.0;
ST=0.5;
TM = 0.0;
SS = IDLE;
WL= 0;
AT= TM + expon(IT); //Arriving
NextServiceTime = expon(ST);
DT= 1.0e+10; // Guaranteeing that the first event is arriving
ProgressAT=0.0;
ProgressDT = 0.0;
}
void Timing()
{
TypeOfEvent = 0;
if(AT < DT)
{
TypeOfEvent = 1;
TM=AT;
}
else
{
TypeOfEvent = 2;
TM= DT;
}
if (TypeOfEvent == 0)
{
cout<<"System Idle "<<TM;
exit(1);
}
}
void Arrival()
{
if (SS == BUSY)
{
++WL;
ServiceTime[WL] = NextServiceTime;
}
else
{
SS = IDLE;
DT = TM + NextServiceTime;
}
AT = TM + expon(IT);
NextServiceTime = expon(ST);
}
void Departure()
{
if (WL == 0)
{
SS= IDLE;
DT = 9999;
}
else
{
if(choice==2)
{
DT= TM + NextServiceTime;
}
--WL;
}
}

Dijkstra's Algorithm issue [repost]

I realized I can't post answers to my own questions because of my low rep or whatever so i deleted my old question and am reasking it. i changed some things and still can't get what i'm looking for.
Here is most of the code
I left out some of the simpler implementations such as parts of the pathFinder class because I know for sure they work, which is why you'll see playerVertex and time just randomly there.
In the example they used a decreaseKey function, I'm not sure if THAT'S what I'm missing? I'm a beginner here, so constructive criticism is welcome. (hopefully as polite as possible) lol. My problem is printing the path, I get a looop of the same two values over and over again.
class Heap
{
public: Heap();
~Heap();
void insert(double element);
double deletemin();
void print();
int size(){return heap.size();}
private:
int currentIndex;
int left(int parent);
int right(int parent);
int parent(int child);
void heapifyup(int index);
void heapifydown(int index);
private:
vector<double> heap;
};
Heap::Heap()
{
currentIndex = 0;
}
Heap::~Heap()
{}
void Heap::insert(double element)
{
heap.push_back(element);
currentIndex++;
heapifyup(heap.size() - 1);
}
double Heap::deletemin()
{
double min = heap.front();
heap[0] = heap.at(heap.size()-1);
heap.pop_back();
heapifydown(0);
currentIndex--;
return min;
}
void Heap::print()
{
vector<double>::iterator pos = heap.begin();
cout << "Heap = ";
while ( pos != heap.end() )
{
cout << *pos;
++pos;
cout << endl;
}
}
void Heap::heapifyup(int index)
{
while((index>0) && (parent(index) >=0) && (heap[parent(index)] > heap[index]))
{
double tmp = heap[parent(index)];
heap[parent(index)] = heap[index];
heap[index] = tmp;
index = parent(index);
}
}
void Heap::heapifydown(int index)
{
int child = left(index);
if((child > 0) && (right(index) > 0) && (heap[child]>heap[right(index)]))
{
child = right(index);
}
if(child > 0)
{
double tmp = heap[index];
heap[index] = heap[child];
heap[child] = tmp;
heapifydown(child);
}
}
int Heap::left(int parent)
{
int i = ( parent <<1) + 1;
return(i<heap.size()) ? i : - 1;
}
int Heap::right(int parent)
{
int i = ( parent <<1) + 2;
return(i<heap.size()) ? i : - 1;
}
int Heap::parent(int child)
{
if(child != 0)
{
int i = (child - 1) >>1;
return i;
}
return -1;
}
class pathFinder : public weightedGraph
{
private:
vertex* playerVertex;
double time;
public:
string source;
pathFinder()
{
playerVertex = NULL;
time = 0;
}
void Dijkstra(int s,int t)
{
vertex *verts = findVertex(grid[s][t]);
Heap H;
for each(vertex *v in vertexList)
{
if(v->data == verts->data)
{
verts->distance = 0;
verts->pred = NULL;
}
v->distance = INFINITY;
v->pred = NULL;
H.insert(v->data);
}
while(H.size() != 0)
{
vertex *x = findVertex(H.deletemin());
for each(edge *v in x->adjacencyList)
{
if(v->end->visited != true)
{
relax(x,v->end);
v->end->visited = true;
}
else
break;
}
}
}
void relax(vertex *a, vertex *b)
{
if(a->distance + weightFrom(a,b) > b->distance)
{
b->distance = a->distance + weightFrom(a,b);
b->pred = a;
}
}
void printPath(double dest,double dest1)
{
vertex *verta = findVertex(dest);
while(verta->pred->data != dest1)
{
cout<<verta->data<<endl;
verta = verta->pred;
}
}
and i'm not sure about the print path being that. i just used the print path from the BFS algorithm i've implemented before.
Where in your printPath function are you looking for the end of the list?
You keep going verta = verta->pred until the data is not equal to some value.
By the way, don't compare doubles for equality, as it ain't going to happen. See What Every Computer Scientist Should Know About Floating Point.
What happens when you single step with your debugger?
(Try drawing the links and how you traverse them.)

How do I make a circular queue thread-safe?

So my Enqueue and Dequeue functions are below. How do I take what I have and make it thread safe? I thought about using a mutex from Windows.h, but I'd like to not limit my program to Windows-only, if possible.
void Queue::Enqueue(int num){
//increase recorded size
size++;
//stick in num
numbers[nextSpace] = num;
//find the next available space
nextSpace = (++nextSpace) % maxSize;
}
int Queue::Dequeue(){
int temp;
temp = items[curSpace];
curSpace = (++curSpace) % maxSize;
size--;
return temp;
}
You can refer this code (with pthreads):
#include<pthread.h>
#define DEFAULT_SIZE 100
class circularQueue{
private:
int *m_queue;
int p_head;
int p_tail;
int m_cap;
pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER;
public:
circularQueue(int size)
{
/*in case invalid input*/
if(size<0)
size = DEFAULT_SIZE ;
m_queue = new int[size];
p_head = 0;
p_tail = -1;
m_cap = 0;
pthread_mutex_init(&mp,NULL);
}
bool enqueue(int x)
{
bool res= false;
p_thread_mutex_lock(&mp);
/*queue is full*/
if(m_cap == size)
{
res = false;
}
else
{
m_queue[(++p_tail)%size)] = x;
++m_cap;
res = true;
}
p_thread_mutex_unlock(&mp);
return res;
}
int dequeue()
{
int res=0;
pthread_mutex_lock(&mp);
/*empty queue*/
if(m_cap == 0)
{
throw("empty queue!");
pthread_mutex_unlock(&mp);
}
else{
res = m_queue[p_head];
p_head = (p_head+1)%size;
}
pthread_mutex_unlock(&mp);
return res;
}
~virtual circularQueue()
{
delete[] m_queue;
m_queue = NULL;
pthread_mutex_destroy(&mp);
}
}

Question about bool in C++

I was wondering why the code below only returns "Test" four times, instead of five?
#include <iostream>
#include <cassert>
using namespace std;
class CountDown
{
public: //Application Programmer Interface
CountDown(int start); // it is set to start
void next(); // subtracts one from it
bool end()const; //
private:
int it;
};
CountDown::CountDown(int start)
{
it = 0;
it = start;
}
void CountDown::next()
{
it = it - 1;
}
bool CountDown::end() const
{
if (it <= 0)
cout << "The countdown is now over" << endl;
}
int main()
{
for( CountDown i = 5 ; ! i.end(); i.next())
std::cerr << "test\n";
}
There is no point in doing this double initialization:
CountDown::CountDown(int start)
{
it = 0;
it = start;
}
This is enough:
CountDown::CountDown(int start)
{
it = start;
}
Or even this, using the initialization list:
CountDown::CountDown(int start):it(start)
{
}
As for end() you don't return any value from it. The method should probably look like this:
bool CountDown::end() const
{
return it <= 0;
}
try this.
bool CountDown::end() const
{
if (it > 1) return false;
return true;
}