This is some code I'm working on for school. When I run it I get a bad_alloc error. It's most likely somewhere in the class definitions, but nothing i tried works. Can someone tell me where the bad allocation is happening?
#include <iostream>
#include <vector>
using namespace std;
enum Dir
{
LEFT = 1,
RIGHT = 1 << 1,
UP = 1 << 2,
DOWN = 1 << 3,
};
class Cell
{
friend class Board;
int row_, col_;
bool visited_;
unsigned int walls_;
Cell* up_;
Cell* down_;
Cell* left_;
Cell* right_;
Cell& set_up(Cell *up)
{
up_ = up;
return *this;
}
Cell& set_down(Cell *down)
{
down_ = down;
return *this;
}
Cell& set_left(Cell *left)
{
left_ = left;
return *this;
}
Cell& set_right(Cell *right)
{
right_ = right;
return *this;
}
public:
Cell( int row = -1, int col = -1)
:row_(row), col_(col), visited_(false), walls_(LEFT | RIGHT | UP | DOWN){}
bool visited() const
{
return visited_;
}
bool hasWall(Dir d) const
{
return walls_ & d;
}
void drill(Dir d)
{
walls_ &= ~d;
}
void draw(int step = 20) const
{
cout << col_*step << " " << row_*step << " " << "moveto" << endl;
cout << step << " " << 0 << " " << (hasWall(DOWN)?"rlineto":"rmoveto") << endl;
cout << 0 << " " << step << (hasWall(RIGHT)?"rlineto":"rmoveto") << endl;
cout << -step << " " << 0 << " " << (hasWall(UP)?"rlineto":"rmoveto") << endl;
cout << 0 << " " << -step << (hasWall(DOWN)?"rlineto":"rmoveto") << endl;
}
Cell* up() const
{
return up_;
}
Cell* down() const
{
return down_;
}
Cell* left() const
{
return left_;
}
Cell* right() const
{
return right_;
}
};
class Board
{
friend class Cell;
int rows_, cols_;
vector<Cell> cells_;
public:
Board(int rows, int cols)
: rows_(rows), cols_(cols)
{
for(int i = 0; i < rows_; i++)
for (int j = 0; i < cols_; j++)
cells_.push_back(Cell(i, j));
for (int i = 0; i < rows_ ; i++)
for(int j = 0; j < cols_; j++)
{
Cell& c = at(i, j);
if(i < rows_ - 1)
c.set_up(&at(i + 1 , j));
if(i > 0)
c.set_down(&at(i - 1 , j));
if(j > 0)
c.set_left(&at(i , j - 1));
if(j < cols_ - 1)
c.set_right(&at(i, j + 1));
}
}
Cell& at(int i, int j)
{
int index = i*cols_ + j;
return cells_[index];
}
const Cell& at(int i, int j) const
{
int index = i*cols_ + j;
return cells_[index];
}
void draw() const
{
cout << "newpath" << endl;
for (vector<Cell>::const_iterator it = cells_.begin(); it != cells_.end(); ++it)
{
(*it).Cell::draw();
}
cout << "stroke" << endl;
cout << "showpage" << endl;
}
};
int main()
{
Board b(5, 5);
Cell& c = b.at(2, 2);
c.drill(UP);
Cell* up = c.up();
up->drill(DOWN);
b.draw();
return 0;
}
Board constructor - second for() you have wrong termination condition. There should be "j < cols_" instead of "i < cols_".
Related
I need some help to understand how to implement the constructor in the Rational class.
I try to send the numerator(p1) and denominator(p2) by reference to the rational class however it start both of them to "0" and not copy them.
the idea is to create rational that contain two Polynomial (numerator and denominator) and print them.
I didn't add all the code just what I think is relevant.
class Polynomial
{
private:
double *varibles;
static int degree;
public:
Polynomial(double * var = NULL, static int deg = NULL);
Polynomial(static int deg );
};
class Rational
{
private:
Polynomial numerator;
Polynomial denominator;
public:
Rational(const Polynomial& p1 , const Polynomial & p2 );
cpp file
Rational::Rational(const Polynomial& p1 , const Polynomial & p2 )
{
this->numerator = p1;
this->denominator = p2;
}
Polynomial::Polynomial(double * var, static int deg) {
if (deg < (sizeof(var) / sizeof(double)))
var = (double*)realloc(var, deg * sizeof(double));
this -> degree = deg;
this -> varibles = var;
}
Polynomial::Polynomial(static int deg) {
this->degree = deg;
this->varibles = (double*)calloc(deg, sizeof(double));
}
void Polynomial::setCoeff(int index, double num) {
if (!this->degree)
Polynomial(index);
this->varibles[index] = num;
}
void Polynomial::SetPolynomial(Polynomial& p) {
int size = p.degree;
int i;
for (i = 0; i < size; i++) {
cout << "Enter Number for X^ " << i+1 << " varibles" << endl;
cin >> p.varibles[i];
}
}
double Polynomial::getDegree(bool what) const {
if (what == false)
return this->degree;
else
return 0;
}
double Polynomial::getCoeff(int index) const {
return this->varibles[index];
}
int Polynomial::getMaxDegree() {
return degree;
}
void Polynomial::print() {
int size = this->degree ; // -1 ?
int i;
if (!this->degree)
cout << "Polynomial = 0";
else {
while (this->varibles[size] == 0)
size--;
if (size < 1 && this->varibles[0] == 0) {
cout << "Polynomial = 0";
}
else {
for (i = 0; i < size; i++) {
if (i == 0)
cout << this->varibles[i] << "+";
else
cout << this->varibles[i] << "X^" << i << "+";
}
cout << this->varibles[i] << "X^" << i ;
}
}
cout << endl;
}
main / test
void testRational() {
Rational r1;
r1.print();
double c[] = { 0,2,2,3,4,5 };
Polynomial p1(c, 5);
p1.print();
c[0] = 1.2;
Polynomial p2(c, 3);
Rational r2(p1, p2);
cout << "test8" << endl;
r2.print();
Code given below is not executed completely;
I have looked for everything on web but I don't know why it is working for starting numbers from nums (i.e. 1000 and sometimes 5000) and after that it starts execution but in between program terminates itself and stopes working.
#include <bits/stdc++.h>
// #include <iostream>
// #include <chrono>
// #include <vector>
#define UPPER_LIMIT 10
using namespace std;
using namespace std::chrono;
bool inTimeLimit = true;
bool isFinished = false;
bool isRunning = true;
class Timer {
public:
time_point<high_resolution_clock> start, end;
Timer() {
start = high_resolution_clock::now();
}
~Timer() {
end = high_resolution_clock::now();
auto durationTime = durationCounter();
cout << "\n\nTaken time Duration " << (unsigned long long)durationTime << " us; " << (unsigned long long)durationTime * 0.001 << "ms.";
}
float durationCounter() {
auto currTime = high_resolution_clock::now();
auto durationTime = duration_cast<microseconds>(currTime - start);
return durationTime.count();
}
};
void printVector(vector <int> v) {
cout << endl;
for (int x : v) {
cout << setw(3) << x << " ";
}
}
void printVectorToFile(ofstream &fout , vector <int> v, string msg) {
fout << "\n\n===================\n\n";
fout << msg << endl;
fout << endl;
for (int x : v) {
fout << setw(5) << x << " ";
}
fout << endl;
}
void swap (int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
vector <int> randomArrayGenerator(int n) {
vector<int> v(n);
for (int i = 0; i < n; ++i)
v[i] = i + 1;
srand(time(0));
for (int i = 0; i < n; ++i)
{
int pos = rand() % n;
swap(&v[i], &v[pos]);
}
return v;
}
string sortingChecker(vector<int> v) {
for (int i = 0; i < (int)v.size() - 1; ++i)
{
if (v[i] > v[i + 1]) return "false";
}
return "true";
}
bool sortChecker(vector<int> v) {
for (int i = 0; i < (int)v.size() - 1; ++i)
{
if (v[i] > v[i + 1]) return false;
}
return true;
}
// Merge function
void merge(vector <int> &v, int begin, int middle, int end) {
vector <int> left, right;
for (int i = begin; i < middle + 1; ++i)
{
left.push_back(v[i]);
}
for (int i = middle + 1; i <= end; ++i)
{
right.push_back(v[i]);
}
int p1 = 0, p2 = 0, n1 = left.size(), n2 = right.size(), p = begin;
while ((p1 < n1 ) || (p2 < n2)) {
if ((p1 != n1 ) && ((p2 == n2) || left[p1] < right[p2]))
v[p++] = left[p1++];
else
v[p++] = right[p2++];
}
}
void mergeSortByIteration(vector <int> &v, bool &isTimeDelayed) {
int low = 0, high = v.size();
cout << "Thread ID: " << this_thread::get_id() << endl;
// n :for taking individual block of vector containing number of elements n=[1,2,4,8,..]
for (int n = 1; n < high; n *= 2) {
if (isTimeDelayed) return;
// taking block according to n and then sorting them by merge function
// n=1 => i=0,2,4,8,16
// n=2 => i=0,4,8
for (int i = 0; i < high; i += 2 * n) {
if (isTimeDelayed) return;
int begin = i;
int mid = i + n - 1;
int end = min(i + 2 * n - 1 , high - 1);
merge(v, begin, mid, end);
}
}
}
// Merge by recurision
void mergeSortByRecursion (vector <int> &v, int begin, int end, bool &isTimeDelayed) {
if (end <= begin || isTimeDelayed) return;
int middle = begin + (end - begin) / 2;
mergeSortByRecursion(v, begin, middle, isTimeDelayed);
mergeSortByRecursion(v, middle + 1, end, isTimeDelayed);
merge(v, begin, middle, end);
}
int main() {
int nums[] = {1000, 5000, 10000, 50000, 100000};
// int nums[] = {50000};
ofstream vectorOutput ;
vectorOutput.open("outputTexts\\prac1_resultedArrays.txt", ios::trunc);;
for (int n : nums)
// ``````` Merge by Iteration ````````
{
vector<int> num, arr = randomArrayGenerator(n);
cout << "\n=======";
cout << "\n\nMerge by Iteration:" << endl;
num = arr;
cout << "Array size: " << num.size() << endl;
bool isTimeOut = false, isSorted = false;
Timer timer;
std::thread worker(mergeSortByIteration, ref(num), ref(isTimeOut));
// mergeSortByIteration(num, isTimeOut);
// std::thread worker(mergeSortByRecursion, ref(num), 0, n - 1, ref(isTimeOut));
while ( ( ( timer.durationCounter() / 1000000 ) < 5) && (!isSorted ) ) {
// this_thread::sleep_for(seconds(1));
// cout << timer.durationCounter() << " ";
isSorted = sortChecker(num);
}
if ( ( ( ( timer.durationCounter() / 1000000 ) > 5) && (!isSorted ) ) )
{
isTimeOut = true;
cout << endl << "!!!!!Execution Terminated ---- Time Limit reached!!!!!!" << endl;
}
if (worker.joinable())
worker.join();
printVector(num);
cout << "\nCheck result for sorted Vector:" << (isSorted ? "true" : "false") << endl;
// printVectorToFile(vectorOutput, num, "Merge By Iteration for size:" + to_string(n) );
}
cout << "\n\ndone" << endl;
return 0;
}
can anyone help me out here?
If issue is not clear fill free to ask.
I'm trying to get this code to sort names but it doesn't seem to work for me. What could be wrong? I have a class named Student and want to pass the names and sort them in ascending order. So what I am trying to do is pass the 4 object firstname onto the the sort_list function and sort them in ascending order and display them afterwards. However when I run the code it shows me the same order I had and the sort function didn't seem to have done anything. See if you guys can help me out here.
#include <iostream>
#include<string>
using namespace std;
//***************************************************************************
//STUDENT CLASS
//***************************************************************************
class Student
{
private:
string firstname;
string lastname;
string studentID;
string phoneNumber;
double gpa;
public:
Student();
Student(const string&, const string&, const string&, const string&, const double&);
string getfirstName() const;
string getlastName() const;
string getstudentId() const;
string getphoneNumber() const;
double getGPA() const;
void setfirstName(string&);
void setlastName(string&);
void setstudentId(string&);
void setphoneNumber(string&);
void setGAP(double&);
};
Student::Student()
{
firstname = " ";
lastname = " ";
studentID = " ";
phoneNumber = " ";
gpa = 0;
}
Student::Student(const string&a, const string&b, const string&c, const string&d, const double&e)
{
firstname = a;
lastname = b;
studentID = c;
phoneNumber = d;
gpa = e;
}
string Student::getfirstName()const
{
return firstname;
}
string Student::getlastName()const
{
return lastname;
}
string Student::getstudentId() const
{
return studentID;
}
string Student::getphoneNumber() const
{
return phoneNumber;
}
double Student::getGPA() const
{
return gpa;
}
void Student::setfirstName(string&u)
{
firstname = u;
}
void Student::setlastName(string&v)
{
lastname = v;
}
void Student::setstudentId(string&x)
{
studentID = x;
}
void Student::setphoneNumber(string&y)
{
phoneNumber = y;
}
void Student::setGAP(double&z)
{
gpa = z;
}
//***************************************************************************
//COURSE CLASS
//***************************************************************************
class Course :public Student
{
private:
string code;
int section;
int capacity;
int numStudents;
Student *list;
public:
Course();
Course(string, int, int);
~Course();
string getCourseCode();
int getSection();
int getCapacity();
int getNumStudents();
void setCourseCode(string);
void setSection(int);
void add(const Student&);
void display();
void display(const string, const int);
void remove(const string m, const int n);
void sort_list();
};
Course::Course()
{
code = "CMPT1020";
section = 1;
capacity = 35;
numStudents = 0;
list = new Student[35];
}
Course::Course(string a, int b, int c)
{
code = a;
section = b;
capacity = c;
numStudents = 0;
list = new Student[c];
}
Course::~Course()
{
delete[] list;
list = nullptr;
}
string Course::getCourseCode()
{
return code;
}
int Course::getSection()
{
return section;
}
int Course::getCapacity()
{
return capacity;
}
int Course::getNumStudents()
{
return numStudents;
}
void Course::setCourseCode(string a)
{
code = a;
}
void Course::setSection(int b)
{
section = b;
}
void Course::add(const Student& s)
{
if (numStudents == capacity)
{
cout << "Course is full" << endl;
return;
}
list[numStudents] = s;
numStudents++;
int i = numStudents - 2;
while (i >= 0 && (s.getGPA() > list[i].getGPA()))
{
list[i + 1] = list[i];
i--;
}
list[i + 1] = s;
}
void Course::display()
{
for (int i = 0; i < numStudents; i++)
{
cout<<list[i].getfirstName() <<" "<< list[i].getlastName() <<" "<< list[i].getstudentId() <<" "<< list[i].getphoneNumber() <<" "<< list[i].getGPA() << endl;
}
}
void Course::display(const string x, const int y)
{
if (y == 1)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getfirstName() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 2)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getlastName() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 3)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getstudentId() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 4)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getphoneNumber() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
}
void Course::remove(const string a, const int b)
{
if (b == 1)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getfirstName() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 2)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getlastName() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 3)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getstudentId() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 4)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getphoneNumber() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
}
void Course::sort_list()
{
string temp;
for (int i = 0; i < numStudents; i++)
{
for (int j = 0; j < numStudents-1; j++)
{
if(list[j].getfirstName() >list[j+1].getfirstName())
{
temp = list[j].getfirstName();
list[j].getfirstName() = list[j+1].getfirstName();
list[j+1].getfirstName() = temp;
}
}
}
}
int main()
{
Student a("Kevin", "Chen", "300215915", "7788408028", 2);
Student b("Mickey", "Mouse", "12345678", "2222222222", 2.5);
Student c("Donald", "Duck", "24681012", "3333333333", 3.0);
Student d("Goofy", "Dog", "3579111315", "5555555555", 3.5);
Course x;
x.add(a);
x.add(b);
x.add(c);
x.add(d);
x.display();
cout << endl;
x.sort_list();
x.display();
/*cout << " " << endl;
x.remove("kevin", 1);
x.remove("Chen", 2);
x.remove("300215915", 3);
x.remove("7788408028", 4);
x.display();
cout << endl;
x.display("kevin", 1);
x.display("Mouse", 2);
x.display("24681012", 3);
x.display("5555555555", 4);*/
system("pause");
return 0;
}
It is true that your sorting code doesn't do anything.
Here is the core of it:
temp = list[j].getfirstName();
list[j].getfirstName() = list[j+1].getfirstName();
list[j+1].getfirstName() = temp;
getfirstName() returns the first name by value so all your assignments are doing is swapping temporary copies of the first names. There is no effect on the actual list elements.
I think you meant:
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
This also means temp must be declared as a Student, not a std::string.
Also, unless I'm misremembering how Bubble Sort works (which is certainly possible — given its uselessness in the real world, it's been a long time since I've written one), your outer loop needs as many iterations as it takes for the inner loop not to be doing any swaps any more. If that's somehow inherently capped at numStudents iterations, I can't see why, nor see any evidence of it on the Wikipedia article.
Assuming I am on the right lines with that, I'd have the function looking like this:
void Course::sort_list()
{
bool go_again = false;
do {
go_again = false;
for (int i = 0; i < numStudents-1; i++) {
if (list[i].getfirstName() > list[i+1].getfirstName()) {
Student temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
go_again = true;
}
}
} while(go_again);
}
(live demo)
When I execute this code in Code::Blocks I get a segmentation fault. Why? I've used debug and haven't found why. Any help is useful.
The debugger showed it was from the vector push_back method, but specifically on the "this" pointer used in the copy constructor.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
const int MAX_COL = 7, MAX_ROW = 6;
const int NOPLAYER = 0, PLAYER1 = 1, PLAYER2 = 2;
const int NOTHING = 123;
int movesBeingStored = 0;
int movesCreated = 0;
class Move{
public:
Move() : row(-1), col(-1), plr(-1) {
//std::cout << "Placed #" << col << "," << row << std::endl;
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
};
Move(int r, int c, int p) : row(r), col(c), plr(p) {
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
};
~Move() {
--movesBeingStored;
std::cout << "-Now " << movesBeingStored << " move(s)" << std::endl;
};
int getRow() const { return row; }
int getCol() const { return col; }
int getPlayer() const { return plr; }
Move(const Move* other) {
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
col = other->getCol();
row = other->getRow();
plr = other->getPlayer();
}
Move(const Move& other) {
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
col = other.getCol(); //This line causes a segment fault
row = other.getRow();
plr = other.getPlayer();
}
bool operator== (const Move& other) const {
return (&other == this);
}
private:
int row, col, plr;
};
int board[MAX_COL * MAX_ROW];
std::vector<Move> moves;
bool isFull[MAX_COL];
int tops[MAX_COL];
int currentPlayer = PLAYER1;
int checkedCollumns = 0;
void randomize( void ) { srand(time(NULL)); }
void startBoard( void );
void placeMove(int col, int player);
void popMove();
int checkwin(int curPlayer);
int checkMove(int depth, int& bestCol, int curP, int checkP);
int randomInt(int min, int max);
void printMoves( void );
int main()
{
startBoard();
randomize();
int col = -1;
int pts = checkMove(2, col, PLAYER1, PLAYER1);
if(col == -1) {
std::cout << "No best move" << std::endl;
} else {
std::cout << "Best move: Col " << col << std::endl;
if(pts == NOTHING) {
std::cout << "Nothing happens" << std::endl;
} else {
std::cout << "Gives " << pts << " points" << std::endl;
}
}
}
void startBoard( void ) {
for(int i = 0; i < MAX_COL; ++i) {
isFull[i] = false;
tops[i] = 0;
}
for(int p = 0; p < MAX_COL * MAX_ROW; ++p) {
board[p] = NOPLAYER;
}
}
void placeMove(int col, int player) {
if(col < 0 || col >= MAX_COL)
return;
if(isFull[col])
return;
if(player != PLAYER1 && player != PLAYER2)
player = PLAYER1;
moves.push_back(Move(col, tops[col], player));
board[col + tops[col] * MAX_COL] = player;
++tops[col];
isFull[col] = (tops[col] == MAX_ROW);
}
void popMove() {
if(moves.empty())
return;
Move move = moves.back();
moves.pop_back();
int col = move.getCol(), row = move.getRow();
board[col + row * MAX_COL] = NOPLAYER;
tops[col] = row;
isFull[col] = (tops[col] == MAX_ROW);
}
int checkwin(int curPlayer) {
if(randomInt(0,5) != 1)
return NOTHING;
return randomInt(0,4);
}
int checkMove(int depth, int& bestCol, int curP, int checkP) {
int pts = NOTHING, col = -1, p = NOTHING, c = -1;
if(depth <= 0) {
if(moves.empty()) {
bestCol = -1;
return NOTHING;
}
Move move = moves.back();
bestCol = move.getCol();
pts = checkwin((move.getPlayer());
if(move.getPlayer() != checkP && pts != NOTHING)
pts = -pts;
return pts;
}
for(int i = 0; i < MAX_COL; ++i) {
std::cout << "C: " << checkedCollumns;
std::cout << "\tD: " << depth;
std::cout << "\tM: " << moves.size();
std::cout << std::endl;
if(isFull[i])
continue;
++checkedCollumns;
placeMove(i, curP);
p = checkMove(depth - 1, c, ((curP == PLAYER1)?PLAYER2:PLAYER1), checkP);
popMove();
if(p != NOTHING && checkP != curP)
p = -p;
if(col == -1) {
col = i;
pts = p;
continue;
}
if(pts == NOTHING && p != NOTHING && p >= 0) {
col = i;
pts = p;
continue;
}
if(pts != NOTHING && p != NOTHING && p > pts) {
col = i;
pts = p;
}
}
bestCol = col;
return pts;
}
int randomInt(int min, int max) {
double per = (double)(rand() % RAND_MAX) / RAND_MAX;
return min + (max - min) * per;
}
void printMoves( void ) {
std::cout << "M:";
if(moves.empty()) {
std::cout << " --\t" << moves.size();
return;
}
Move m;
for(unsigned int i = 0; i < moves.size(); ++i) {
m = moves.at(i);
std::cout << " {" << m.getCol() << "," << m.getRow() << "}";
}
std::cout << "\t" << moves.size();
}
A very trivial error, manifesting in a very obscure way. The segment fault is caused by the vector trying to construct an object at an invalid location. Why? Because of the following line in void popMove():
board[col + row * MAX_COL] = NOPLAYER;
This line has a buffer overflow caused by invalid coordinates (0, 6), which overwrites the internal memory pointer in moves. That's the problem, the solution is up to you.
My question is what am I doing wrong. The insert function doesn't work correctly. I am unable to retrieve the list itself. And because of this my selection sort won't execute. Any help would be appreciated.
Header:
/** #file ListA.h */
#include <string>
using namespace std;
const int MAX_LIST = 100;
typedef string ListItemType;
class List
{
public:
List();
bool isEmpty() const;
int getLength() const;
void insert(int index, const ListItemType& newItem, bool& success);
void retrieve(int index, ListItemType& dataItem, bool & success) const;
void remove(int index, bool& success);
int selectionSortArray(int numdata[], int xnums);
List selectionSort(List selectList);
private:
ListItemType items[100];
int size;
int translate(int index) const;
};
CPP:
/** #file ListA.cpp */
#include "ArrayList.h" // header file
#include <iostream>
#include <fstream>
List::List() : size()
{
}
bool List::isEmpty() const
{
return size == 0;
}
int List::getLength() const
{
return size;
}
void List::insert(int index, const ListItemType& newItem, bool& success)
{
success = (index >= 1) &&
(index <= size + 1) &&
(size < MAX_LIST);
if (success)
{
for (int pos = size; pos >= index; --pos)
items[translate(pos + 1)] = items[translate(pos)];
items[translate(index)] = newItem;
++size;
}
}
void List::remove(int index, bool& success)
{
success = (index >= 1) && (index <= size);
if (success)
{
for (int fromPosition = index + 1;
fromPosition <= size;
++fromPosition)
items[translate(fromPosition - 1)] = items[translate(fromPosition)];
--size; // decrease the size of the list by one
} // end if
} // end remove
void List::retrieve(int index, ListItemType& dataItem,
bool& success) const
{
success = (index >= 1) && (index <= size);
if (success)
dataItem = items[translate(index)];
}
int List::translate(int index) const
{
return index - 1;
}
//List List::selectionSort(List selectList)
//{
//return selectList;
int List::selectionSortArray(int numdata[], int xnums)
{
int tmp;
for (int i = 0; i < xnums -1; i++)
for (int j = i+1; j < xnums; j++)
if (numdata[i] > numdata[j])
{
tmp = numdata[i];
numdata[i] = numdata[j];
numdata[j] = tmp;
}
//for( int i = 0; i < 5; i++)
//cout << numdata[i] << " ";
return *numdata;
}
int main()
{
ListItemType insertType = "listItem1";
ListItemType retrieveType = "listitem2";
int numberofitems;
cout << "Please enter the number of data items:" << endl;
cin >> numberofitems;
cout << endl;
cout << "Please enter the data items, one per line:" << endl;
int listofitems[numberofitems];
List myArrayList;
cout << myArrayList.getLength() << endl;
if (myArrayList.isEmpty()) // tests before
{
cout << "This list is empty \n" << endl;
}
else
{
cout << "List is not empty! \n"<< endl;
}
bool mainsucc = true;
for (int i = 0; i<numberofitems; i++)
{
cout << "Enter number " << i+1 << " : " << endl;
cin >> listofitems[i];
}
for (int i =0; i <numberofitems; i++){
myArrayList.insert(listofitems[i], insertType, mainsucc);}
cout << "Size of the list is : " << myArrayList.getLength() << endl;
int listRetrieveSize = myArrayList.getLength();
int listRetrieve[listRetrieveSize];
for (int j=0; j<listRetrieveSize; j++)
{
myArrayList.retrieve(listofitems[j], retrieveType, mainsucc);
}
if (myArrayList.isEmpty()) // tests after
{
cout << "This list is empty \n" << endl;
}
else
{
cout << "List is not empty! \n"<< endl;
}
numberofitems= myArrayList.selectionSortArray(listofitems, numberofitems);
for (int i=0;i>numberofitems;i++)
{
cout<<listofitems[i];
}
return 1;
}
Your selection sort is definitely wrong:
int List::selectionSortArray(int numdata[], int xnums)
{
int tmp;
for (int i = 0; i < xnums -1; i++) {
//you should find the smallest integer inside this for loop
for (int j = i+1; j < xnums; j++) {
if (numdata[i] > numdata[j])
{
//why do you swap inside this for loop?
tmp = numdata[i];
numdata[i] = numdata[j];
numdata[j] = tmp;
}
}//missing closing }
//smap numdata[i] with currently smallest int
}//missing closing }
return *numdata;
}
Your insert function deals with strings, but you are doing selection sort on integers.
typedef string ListItemType;
defines string as ListItemType.
I'm pretty sure that what you have implemented is the Bubble sort algorithm, instead of the selection sort algorithm.