can't solve error c2280 C++ - c++

i have a c2280 error in c++ and i don't know how to solve it.
here is the code:
#include <iostream>
#include <queue>
#include <deque>
#include "State.h"
#include <assert.h>
#define MAXIMUM_NUMBER_OF_STATES 1000
#define DELTA_Q 0.1
using namespace std;
class RRT
{
private:
float inc_dist;
State start;
State goal;
deque<State> states = deque<State>();
bool goal_is_reached = false;
float RRT::random(float min, float max){
// check if min is less than max , if not then exception is thrown
assert(max >= min);
float range = max - min;
float random;
random = rand() / RAND_MAX;
return (random * (range)) + min;
}
State RRT::randomState(State current_state){
State state = State();
srand(time(0));
while (inStates(state))
{
state.x = random(min(current_state.x, goal.x), max(current_state.x, goal.x));
state.y = random(min(current_state.y, goal.y), max(current_state.y, goal.y));
state.z = random(min(current_state.z, goal.z), max(current_state.z, goal.z));
}
return state;
}
bool RRT::inStates(State state){
for (int i = 0; i < states.size(); i++){
if (states.at(i).x == state.x && states.at(i).y == state.y && states.at(i).z==state.z)
return true;
}
return false;
}
bool RRT::goalTest(State state){
if (state.x == goal.x && state.y == goal.y && state.z == goal.z){
return true;
}
else
return false;
}
void RRT::Successor(State state){
State temp3;
State temp2;
cout <<endl<< "was"<<endl;
if (goalTest(state) || states.size() == MAXIMUM_NUMBER_OF_STATES){
return;
}
getNearistNeighbor(temp3=randomState(state));
cout << "random x: " << temp3.x << " random y: " << temp3.y << " random z: " << temp3.z << endl;
temp2 = State(temp3);
temp2.setFather(state);
states.push_back(temp2);
states.back().setFather(state);
Successor(states.back());
return;
}
State RRT::getNearistNeighbor(State sub_goal_state){
float min_dist = 0, temp;
State desired_state;
for (int i = 0; i < states.size(); i++){
temp = distanceBetweenTwoStates(states.at(i), sub_goal_state);
if (temp < min_dist){
min_dist = temp;
desired_state = State(states.at(i));
}
}
return desired_state;
}
void RRT::generatePath(State state){
cout << endl << "1" << endl;
if (!state.checkIfNull()){
cout << endl << "end" << endl;
return;
cout << endl << "2" << endl;
generatePath(*state.getFather().get());
path.push_back(state);
}
cout << endl << "2" << endl;
generatePath(*state.getFather().get());
path.push_back(state);
return;
}
float RRT::distanceBetweenTwoStates(State state1, State state2){
float x_distance, y_distance, z_distance;
x_distance = sqrt(pow((state1.x - state2.x), 2));
y_distance = sqrt(pow((state1.y - state2.y), 2));
z_distance = sqrt(pow((state1.z - state2.z), 2));
return x_distance + y_distance + z_distance;
}
public:
deque<State> path = deque<State>();
deque<float*> xyzs = deque<float*>();
RRT::RRT(){
}
RRT::RRT(float* starting_point, float* goal_point)
{
start = State(starting_point);
goal= State(goal_point);
states.push_back(start);
}
deque<float*> RRT::getPath(){
Successor(start);
for (int i = 0; i < states.size();i++)
{
if (goalTest(states.at(i))){
goal_is_reached = true;
path.push_back(states.at(i));
break;
}
}
if (goal_is_reached==false){
path.push_back(getNearistNeighbor(goal));
}
State state;
state=State(path.at(0));
path.pop_front();
cout << endl << "x: " << state.x;
cout << endl << "y: " << state.y;
cout << endl << "z: " << state.z << endl;
generatePath(state);
convertToXYZ();
return xyzs;
}
void convertToXYZ(){
State temp;
float* xyz = new float[3];
for (int i = 0; i < path.size(); i++){
temp = path.at(i);
xyz[0] = temp.x;
xyz[1] = temp.y;
xyz[3] = temp.z;
xyzs.push_back(xyz);
}
}
};
here is the code for State.h:
#include <memory>
using namespace std;
class State
{
private:
unique_ptr<State> father;
public:
float x;
float y;
float z;
State(float *xyz){
x = 0;
y = 0;
z = 0;
father = NULL;
}
State(){
x = 0;
y = 0;
z = 0;
father = NULL;
}
State(State& state) : father(new State(*state.father)), x(state.x), y(state.y), z(state.z) {}
State(unique_ptr<State>& state) : father(new State(*state.get())){}
void setFather(State& state){
father.reset(new State(state));
}
unique_ptr<State> getFather(){
unique_ptr<State> temp(new State(*this));
return temp;
}
bool checkIfNull(){
if (father){
return true;
}
else
return false;
}
};
i have been trying to solve this problem but i have not succeed so i need your help guys please help me in solving this.
thanks in advance.
here is the error:
Error 8 error C2280: 'std::unique_ptr<State,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function c:\users\userr\documents\visual studio 2013\projects\devo controller\devo controller\rrt.h 186 1 Devo Controller
again thanks in advance.

unique_ptr<State> getFather(){
unique_ptr<State> temp(new State(*this));
return temp;
}
you can't return unique_ptr . returning a value from function means using the copy constructor. the copy constructor is disabled for unique_ptr. why? because you can't copy a unique_ptr , it's unique! you need to use shared_ptr if many pointers are to point to a specific object. the same goes for the assignment operator ( = ) .
PS. I think it's deprecated to explicitly assign object memory addres to unique_ptr (with new) , the new standard forces you to use std::make_unique in order to assign something to unique_ptr.
also, try googling your error first, you'll be surprised how many answers there are out there

Related

I can't find the memory leak [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Could you please tell me where is the memory leak and explain why i did wrong? I can't find the problem and i don't find the answer on google.
#include <iostream>
using namespace std;
class Avion{
private:
static int autoincrementare;
char* nume;
int randuri;
int* locuri ;
const double pret = 100.00;
int nrPersonal;
bool servire;
public:
// setteri si getteri
int getRanduri(){
return this->randuri;
}
int getNrPersonal(){
return this->nrPersonal;
}
bool getServire(){
return this->servire;
}
char* getNume(){
return this->nume;
}
int* getLocuri(){
return this->locuri;
}
void setNume(char* nume){
if (nume != NULL) delete this->nume;
this->nume = new char[strlen(nume) + 1];
strcpy(this->nume, nume);
}
void setLocuri(int* locuri){
if (randuri != NULL) {
this->locuri = new int[this->randuri];
for (int i = 0; i < randuri; i++)
this->locuri[i] = locuri[i];
}
}
void setRanduri(int randuri){
this->randuri = randuri;
}
void setNrPersonal(int nrPersonal){
this->nrPersonal = nrPersonal;
}
void setServire(bool servire){
this->servire = servire;
}
//constructor fara parametrii
Avion() :pret(autoincrementare++){
this->randuri = 3;
this->servire = true;
this->nrPersonal = 10;
this->nume = new char[strlen("Luft") + 1];
strcpy(this->nume, "Luft");
this->locuri = new int[this->randuri];
for (int i = 0; i < this->randuri; i++){
this->locuri[0] = 30;
this->locuri[1] = 40;
this->locuri[2] = 50;
}
}
Avion(int randuri, bool servire, int nrPersonal, char* nume, int* locuri) :pret(autoincrementare++){
this->randuri = randuri;
this->servire = servire;
this->nrPersonal = nrPersonal;
//if (nume != NULL) delete this->nume;
this->nume = new char[strlen(nume) + 1];
strcpy(this->nume, nume);
// if (locuri != NULL)delete this->locuri;
this->locuri = new int(this->randuri);
for (int i = 0; i < randuri; i++)
{
this->locuri[i] = locuri[i];
}
}
friend ostream & operator<<(ostream & out, Avion & a){
out << "Avionul are " << a.randuri << " randuri" << endl;
out << "Avionul are deschis bufetul : " << a.servire << endl;
out << "Avionul are numarul de personal de: " << a.nrPersonal << endl;
out << "Avionul are numele : " << a.nume << endl;
out << " Avionul are: " << a.randuri << " randuri cu " << endl;
for (int i = 0; i < a.getRanduri(); i++){
cout << a.getLocuri()[i] << " locuri " << endl;
}
return out;
}
friend istream & operator >>(istream & in, Avion &a){
char aux[50];
cout << "Nume avion : "; in >> aux;
if (a.nume != NULL) delete[] a.nume;
a.nume = new char[strlen(aux) + 1];
strcpy(a.nume, aux);
return in;
}
Avion& operator=(const Avion& a){
this->randuri = a.randuri;
this->servire = a.servire;
this->nrPersonal = a.nrPersonal;
this->nume = new char[strlen(a.nume) + 1];
strcpy(this->nume, a.nume);
this->locuri = new int(this->randuri);
for (int i = 0; i < randuri; i++)
{
this->locuri[i] = a.locuri[i];
}
return *this;
}
~Avion(){
if (nume != NULL) delete[] this->nume;
if (locuri != NULL) delete[] this->locuri;
}
};
int Avion::autoincrementare = 1;
void main(){
Avion Luft;
cin >> Luft;
cout << Luft << endl;
cout << "================================"<<endl;
cout << "==========================" << endl;
int a[3]{10, 20, 30};
Avion BlueAir(3, true, 10, "Blue Air", a);
cout << BlueAir << endl;
/*
Avion G6;
G6 = Luft;
cout << G6 << endl;
cout << "==================";
cout << Luft << endl;
*/
}
In this code, the first line of the function is doing a delete instead of a delete[]. So that's at least one memory leak.
void setNume(char* nume){
if (nume != NULL) delete this->nume;
this->nume = new char[strlen(nume) + 1];
strcpy(this->nume, nume);
}
You have to match new with delete and new[] with delete[].

C++ none of the 3 overloads could convert all the argument types line 39 1

So after coding this I got an error : C++ none of the 3 overloads could convert all the argument types line 39 1 in w5.cpp
do you know where is the problem? and could you help me to fix it? I actually dont know why it is showing this because I got the default constructor for this code.
//w5.h
#define MAX_LINE_LENGTH 256
#define MAX_PURCHASES 5
// w5.cpp
#include <iostream>
#include <cstring>
#include "w5.h"
#include "CreditStatement.h"
using namespace std;
void sort(CreditStatement* statement, int n);
int main()
{
double price;
int n = 0;
CreditStatement statement[MAX_PURCHASES];
cout << "Credit Statement Processor\n";
cout << "==========================\n";
do
{
cout << "Item price (0 to quit): ";
cin >> price;
if (cin.fail() || (cin.get() != '\n'))
{
cin.ignore(2000, '\n');
cerr << "Bad character. Try again." << endl;
cin.clear();
}
else if ((int)price != 0)
{
cout << "Statement item: ";
char item[MAX_LINE_LENGTH];
cin.getline(item, MAX_LINE_LENGTH);
if (strlen(item) > 0)
{
statement[n] = CreditStatement(item, price);
n++;
}
}
} while ((int)price != 0 && n < MAX_PURCHASES);
cout << endl;
sort(statement, n);
cout << " Credit Statement\n\n";
cout << " Item Price\n";
cout << "----------------------------------\n";
for (int i = 0; i < n; i++)
{
statement[i].display();
}
cout << endl;
return 0;
}
// sort sorts the elements of Credit Card Statement[n] in ascending order
//
void sort(CreditStatement* s, int n)
{
int i, j;
CreditStatement temp;
for (i = n - 1; i > 0; i--)
{
for (j = 0; j < i; j++)
{
if (s[j].isGreaterThan(s[j + 1]))
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
}
//CreditStatement.h
class CreditStatement{
bool _valid;
double* _price;
char* _item;
public:
CreditStatement();
CreditStatement(char*, double*);
CreditStatement(const CreditStatement&);
CreditStatement& operator=(const CreditStatement&);
//output
void display() const;
//mutators
bool isGreaterThan(const CreditStatement&) const;
};
//CreditStatement.cpp
#include <iostream>
#include <new>
#include "CreditStatement.h"
using namespace std;
void CreditStatement::display() const{
cout << " Something" << _price << _item;
}
bool CreditStatement::isGreaterThan(const CreditStatement&) const{
return _valid;
}
CreditStatement::CreditStatement(){
_item = NULL;
_price = NULL;
}
CreditStatement::CreditStatement(char* iP, double* pP){
_price = NULL;
_item = NULL;
if (pP != NULL){
int sizepP = sizeof(pP) / sizeof(pP[0]);
_price = new (nothrow) double[sizepP];
if (_price){
for (int i = 0; i <sizepP; i++){
_price[i] = pP[i];
};
}
if (iP != NULL){
int sizeiP = sizeof(iP) / sizeof(iP[0]);
_item = new (nothrow) char [sizeiP];
if (_item){
for (int i = 0; i < sizeiP; i++){
_item[i] = iP[i];
};
}
}
}
}
CreditStatement::CreditStatement(const CreditStatement& otherCS){
*this = CreditStatement(otherCS._item, otherCS._price);
}
CreditStatement& CreditStatement::operator=(const CreditStatement& otherCS){
if (this != &otherCS)
{
if (_item){
delete[] _item;
_item = NULL;
}
if (_price){
delete[] _price;
_price = NULL;
}
else{
if (otherCS._price != NULL){
int sizepP = sizeof(otherCS._price) / sizeof(otherCS._price[0]);
_price = new (nothrow) double[sizepP];
if (_price){
for (int i = 0; i < sizepP; i++){
_price[i] = otherCS._price[i];
};
}
if (otherCS._item != NULL){
int sizeiP = sizeof(otherCS._item) / sizeof(otherCS._item[0]);
_item = new (nothrow) char[sizeiP];
if (_item){
for (int i = 0; i < sizeiP; i++){
_item[i] = otherCS._item[i];
};
}
}
}
}
}
return *this;
}
I also got this error
"no instance of constructor "CreditStatement::CreditStatement" matches the argument list
argument types are: (char [256], double) c:*\Project1\w5.cpp 38 20.
I think the problem is your call statement[n] = CreditStatement(item, price);
Here, price is a double, but there's a constructor CreditStatement(char*, double*); but none with signature CreditStatement(char*, double);
You might want to fix that.

c++ Function Definition does not declare parameters

I am getting compile errors in my C++ project. On my friend's computer I get no errors but on mine I get the following:
On line 129 - "Function Definition does not declare parameters "
On line 137 - "'seats' was not declared in this scope"
I am running Code::blocks 10.05 on Windows 7.
Here is my code (with line numbers indicated by comments):
#include <iostream>
#include "Seat.h"
using namespace std;
class Plane
{
public:
int viewSeat(int sNum) {
if (seats[sNum].isFree()) {
return 0;
} else {
//cout << "Debug (Plane::viewSeat(sNum) called)";
string seatMess = "";
switch (seats[sNum].getState()) {
case 1:
seatMess = " is reserved for ";
break;
case 2:
seatMess = " has been checked in by ";
break;
}
cout << "(X) Seat ";
cout << seats[sNum].getCode();
cout << seatMess;
cout << seats[sNum].getFName() << " " << seats[sNum].getLName() << "\n";
return 1;
}
}
void viewAll() {
for (int x = 0; x < numOfSeats; x++) {
if ((seats[x].getState() == 0)) {
cout << "Seat " << seats[x].getCode() << " is free\n";
} else {
viewSeat(x);
}
}
}
void viewFree() {
int freeSeats = 0;
for (int x = 0; x < numOfSeats; x++) {
if ((seats[x].getState() == 0)) {
cout << "Seat " << seats[x].getCode() << " is free\n";
freeSeats++;
}
}
cout << "Found " << freeSeats << " free seats\n";
}
void freeSeat(int sNum) {
seats[sNum].emptySeat();
}
string getCode(int sNum) {
return seats[sNum].getCode();
}
int reserveSeat(int sNum, string fName, string lName, int age, int cType, string business = "") {
if (seats[sNum].isFree()) {
seats[sNum].setFName(fName);
seats[sNum].setLName(lName);
seats[sNum].setAge(age);
seats[sNum].setType(cType);
seats[sNum].setState(1);
seats[sNum].setBusiness(business);
return 1;
} else {
return 0;
}
}
int checkSeat(string lName, string seatCode) {
int found = 0;
for (int x = 0; x < (sizeof(seats) / sizeof(Seat)); x++) {
if ((seats[x].getCode() == seatCode) && (seats[x].getLName() == lName)) {
found = 1;
seats[x].setState(2);
return 1;
}
}
return 0;
}
int calcTake() {
int seatPrice = 5;
int totalTake, totalSeats = 0, totalWestern = 0, totalBusiness = 0, totalStandard = 0;
for (int x = 0; x < numOfSeats; x++) {
if ((seats[x].getState() != 0)) {
int cType = seats[x].getType();
int thisSeat;
if (cType == 1) {
// discount for western`
thisSeat = 0.75 * seatPrice;
totalWestern++;
} else if (cType == 2) {
// discount for business
thisSeat = 0.8 * seatPrice;
totalBusiness++;
} else {
thisSeat = 0.95 * seatPrice;
totalStandard++;
}
totalTake = totalTake + thisSeat;
totalSeats++;
}
}
return totalTake;
}
int isFree(int sNum) {
if (seats[sNum].isFree()) {
return 1;
} else {
return 0;
}
}
private:
// Line 129 ("Function Definition does not declare parameters"):
Seat seats[32] { {"1A"}, {"1B"}, {"1C"}, {"1D"},
{"2A"}, {"2B"}, {"2C"}, {"2D"},
{"3A"}, {"3B"}, {"3C"}, {"3D"},
{"4A"}, {"4B"}, {"4C"}, {"4D"},
{"5A"}, {"5B"}, {"5C"}, {"5D"},
{"6A"}, {"6B"}, {"6C"}, {"6D"},
{"7A"}, {"7B"}, {"7C"}, {"7D"},
{"8A"}, {"8B"}, {"8C"}, {"8D"}
};
// Line 137 ("'seats' was not declared in this scope"):
int numOfSeats = sizeof(seats) / sizeof(Seat);
};
I think you have missed =
Seat seats[32] = { {"1A"}, {"1B"}, {"1C"}, {"1D"},..

Crashing when objects are deleted

It's crashing at the very end of the main() function where it needs to delete the starters objects. The error message that pops up when I run the program says: Debug assertion failed! Expression: _BLOCK_IS_VALID(pHead->nBlockUse). How do i fix it from crashing when deleting the starters objects?
#include <iostream>
#include <fstream>
#include "olympic.h"
using namespace std;
ofstream csis;
int main() {
const int lanes = 4;
Ranker rank(lanes);
csis.open("csis.txt");
// First make a list of names and lane assignments.
Competitor* starters[lanes];
starters[0] = new Competitor("EmmyLou Harris", 1);
starters[1] = new Competitor("Nanci Griffith", 2);
starters[2] = new Competitor("Bonnie Raitt", 3);
starters[3] = new Competitor("Joni Mitchell", 4);
// The race is run; now assign a time to each person.
starters[0]->setTime((float)12.0);
starters[1]->setTime((float)12.8);
starters[2]->setTime((float)11.0);
starters[3]->setTime((float)10.3);
// Put everyone into the ranker.
for (int i = 0; i < lanes; i++)
rank.addList(starters[i]);
// Now print out the list to make sure its right.
cout << "Competitors by lane are:" << endl;
csis << "Competitors by lane are:" << endl;
for (int i = 1; i <= lanes; i++)
rank.getLane(i)->print();
// Finally, show how they finished.
cout << "Rankings by finish are:" << endl;
csis << "Rankings by finish are:" << endl;
for (int i = 1; i <= lanes; i++)
rank.getFinish(i)->print();
for (int i = 0; i < lanes; i++)
delete starters[i];
csis.close();
}
ranker.cpp:
#include "ranker.h"
#include "competitor.h"
#include <stdlib.h>
Ranker::Ranker(int lanes) {
athlete = new Competitor*[lanes];
numAthletes = 0;
maxAthletes = lanes;
}
int Ranker::addList(Competitor* starter) {
if (numAthletes < maxAthletes && starter != NULL) {
athlete[numAthletes] = starter;
numAthletes++;
return numAthletes;
}
else
return 0;
}
Competitor* Ranker::getLane(int lane) {
for (int i = 0; i < numAthletes; i++) {
if (athlete[i]->getLane() == lane) {
return athlete[i];
}
}
return NULL;
}
Competitor* Ranker::getFinish(int position) {
switch(position) {
case 1:
return athlete[3];
break;
case 2:
return athlete[2];
break;
case 3:
return athlete[1];
break;
case 4:
return athlete[0];
break;
}
return NULL;
}
int Ranker::getFilled() {
return numAthletes;
}
Ranker::~Ranker() {
delete [] athlete;
}
competitor.h:
#ifndef _COMPETITOR_H
#define _COMPETITOR_H
class Competitor {
private:
char* name;
int lane;
double time;
public:
Competitor(char* inputName, int inputLane);
Competitor();
void setTime(double inputTime);
char* getName();
int Competitor::getLane();
double getTime();
void print();
~Competitor();
};
#endif
competitor.cpp:
#include "competitor.h"
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
Competitor::Competitor(char* inputName, int inputLane) {
name = inputName;
lane = inputLane;
}
Competitor::Competitor() {
name = 0;
lane = 0;
time = 0;
}
void Competitor::setTime(double inputTime) {
time = inputTime;
}
char* Competitor::getName() {
return name;
}
int Competitor::getLane() {
return lane;
}
double Competitor::getTime() {
return time;
}
void Competitor::print() {
cout << setw(20) << name << setw(20) << lane << setw(20) << setprecision(4) << time << endl;
}
Competitor::~Competitor() {
delete [] name;
}
Call stack:
before crash: http://i.imgur.com/d4sKbKV.png
after crash: http://i.imgur.com/C5cXth9.png
After you've added Competitor class, it seems the problem is that you delete its name in Competitor's destructor. But you assign it from string literal which can't really be deleted. I'm sure the stack trace leading to assertion will prove that.
One way of solving the problem would be using std::string to store the name.
Problem is when deleting the char* value on destructor, which is assigned with const char instead new char. So i have slightly changed the constructor to copy the const char to new char.
Competitor::Competitor(char* inputName, int charlen, int inputLane)
{
name = new char[charlen + 1];
memcpy(name , inputName, charlen );
name [charlen] = '\0';
lane = inputLane;
}

Overloading Operator most likely not working [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Could you guys check out my function somethingWrong(), and my overloading operators.
Sometimes when I run the function somethingwrong() I get "True" and sometimes "False".
I am not changing anything, why is this happening?
This is a Dijkstra algorithm graph I am working in.
Thank You
main.cpp:
#include <iostream>
#include <fstream>
#include "graph.h"
using namespace std;
int main(){
//
graph g;
g.addVertices();
//g.printAll();
g.addEdges();
cout << "Hello" << endl;
//g.printAdjList(5.74);
//g.DJAlgorithm();
g.somethingWrong();
return 0;
}
graph.h
#include <iostream>
#include <list>
#include <fstream>
#include "minHeap.h"
using namespace std;
class graph{
protected:
class vertex{
public:
int x;
int y;
double cost;
double weight;
vertex * parent;
list<vertex*> adjacencyList;
vertex(int xc, int yc, double c){
x = xc;
y = yc;
cost = c;
weight = -1;
parent = NULL;
}
// operator overloading
// dont know if to add =
vertex & vertex::operator=(vertex * z){
return *z;
}
bool vertex::operator==(vertex * z){
return (this->weight == z->weight);
}
bool vertex::operator!=(vertex * z){
return (this->weight != z->weight);
}
bool vertex::operator<=(vertex * z){
return (this->weight <= z->weight);
}
bool vertex::operator<(vertex * z){
return (this->weight < z->weight);
}
bool vertex::operator>=(vertex * z){
return (this->weight >= z->weight);
}
bool vertex::operator>(vertex * z){
return (this->weight > z->weight);
}
};
list<vertex*> vertexList;
int numOfVertices;
public:
int sX;
int sY;
int eX;
int eY;
graph(){
numOfVertices = 0;
}
void somethingWrong(){
vertex *dog = new vertex(0,0,0);
vertex * cat = new vertex(0,0,0);
dog->weight = 5;
cat->weight = 9;
if(dog < cat){
cout << "True" << endl;
}
else{
cout << "False" << endl;
}
}
void addVertices(){
ifstream inFile;
double w;
int countX = 1;
int countY = 1;
inFile.open("grid.txt");
if(!inFile){
cout << "Error opening file!" << endl;
return;
}
// get the coordinates of the starting and
// ending position
inFile >> sX;
inFile >> sY;
inFile >> eX;
inFile >> eY;
// get the grid of data
while(!inFile.eof()){
inFile >> w;
vertexList.push_back(new vertex(countX,countY,w));
numOfVertices++;
countX++;
if(inFile.peek() == '\n'){
countX = 1;
countY++;
}
}
}
void addEdges(){
for each(vertex * v in vertexList){
for each(vertex * w in vertexList){
if(((v->x == w->x) && (abs(v->y - w->y)) == 1) || ((v->y == w->y) && (abs(v->x - w->x) == 1))){
v->adjacencyList.push_back(w);
}
}
}
}
// prints all the grid, for verification purposes
void printAll(){
cout << sX << " " << sY << endl;
cout << eX << " " << eY << endl;
for each(vertex * v in vertexList){
cout << v->x << " " << v->y << " " << v->cost << endl;
}
}
// print a vertex's adjacency list
void printAdjList(double c){
for each(vertex * v in vertexList){
if(v->cost == c){
for each(vertex * w in v->adjacencyList){
cout << w->x << " " << w->y << " " << w->cost << endl;
}
return;
}
}
}
// problelm here
// prints the path from vertex x
void printPath(vertex * x){
if(x != NULL){
//cout << "sup" << endl;
printPath(x->parent);
cout << "(" << x->x << "," << x->y << ") weight: " << x->weight << endl;
}
}
void DJAlgorithm(){
// min Heap item
minHeap<vertex*> C(numOfVertices);
vertex * s;
vertex * x;
vertex * e;
// find required start and end vertices
for each(vertex * v in vertexList){
if(v->x == sX && v->y == sY){
s = v;
}
if(v->x == eX && v->y == eY){
e = v;
}
}
// set up all values
for each(vertex * v in vertexList){
v->weight = -1;
v->parent = NULL;
}
s->weight = 0;
// insert everything in to the queue/minHeap
for each (vertex * v in vertexList){
C.insert(v);
}
while(!C.empty()){
x = C.extractMin();
for each(vertex * v in x->adjacencyList){
// relax
// if not discovered
if(v->weight == -1){
v->weight = x->weight;
v->parent = x;
}
// if already discovered
else{
if(x->weight + v->cost < v->weight){
v->weight = x->weight + v->cost;
v->parent = x;
}
}
}
}
// print out the path back
printPath(e);
}
};
// min heap data structure
#include <iostream>
using namespace std;
template<class THING>
class minHeap
{
private:
//array to hold items
THING * items;
int n;
//return index of parent of i
int parent(int i)
{
return (i-1)/2;
}
//return index of left child of i
int lchild(int i)
{
return i*2 + 1;
}
//return index of right child of i
int rchild(int i)
{
return i*2 + 2;
}
//return index of smaller child
int minChild(int i)
{
if( lchild(i) >= n ) //a leaf!
return i;
else if( lchild(i) == (n-1) )
return lchild(i);
else if( items[lchild(i)] < items[rchild(i)] )
return lchild(i);
else
return rchild(i);
}
//bubble item at index current up tree
//until there's no more violation
void bubbleUp(int current)
{
// ignoring all these
if( current == 0 ) //the root! easy!
{
//do nothing, done, no violation, base case!
}
else if( items[current] >= items[parent(current)] ) //no violation
{
//do nothing!, done, go home, base case!
}
else
{
//step 1: swap current with parent
swap( items[current], items[parent(current)] );
//step 2: keep bubbling item up
bubbleUp( parent(current) );
}
}
void bubbleDown(int current)
{
if( lchild(current) >= n ) //current is a leaf....
{
//do nothing! base case!! party down!
}
else if( items[current] <= items[minChild(current)] ) //no violation..
{
//done!1 party down! base case
}
else
{
//step 1: swap with min child
int mchild = minChild(current);
swap( items[current], items[mchild] );
//step 2: continue bubbling down
bubbleDown(mchild);
}
}
public:
minHeap(int cap)
{
items = new THING[cap];
n=0;
}
//return true if heap is empty
bool empty()
{
if( n==0 )
return true;
else
return false;
}
//add item x to heap
void insert(THING x)
{
//step 1: add x to end of array
items[n] = x;
n++;
//step 2: bubble up!
bubbleUp(n-1);
}
//remove and return smallest item in heap
THING extractMin()
{
//step 1: store root item in output box
THING output = items[0];
//step 2: put last item at root
items[0] = items[n-1];
n--;
//step 3: bubble down!
bubbleDown(0);
return output;
}
};
vertex *dog = new vertex(0,0,0);
vertex *cat = new vertex(0,0,0);
if(dog < cat)
Compares two pointers and effectively the addresses. Comparing addresses does not make much sense as they can have any values.
You need to compare two objects:
if(*dog < *cat)
Ofcourse you also need to change the function prototype of the overloaded operator to take this in to account.
vertex & vertex::operator=(vertex * z)
That is an assignment operator that takes a left hand side of type vertex and a right hand side of type vextex*. The usual signature for operator= is:
vertex& operator=(const vertex& rhs);
The latter definition allows for assignment of one object to another object, while the former assigns a pointer to an object.