Errors with Unsorted List? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
So I have a homework assignment due tonight and I'm trying to compile it to test but I'm running into a bunch of errors and some of them seem to make zero sense? The errors mention things like: "syntax error before '::'" and the like, but I have never encountered errors like these and have 0 idea on how to fix them.
UnsortedClass.cpp
#include "UnsortedClass.h"
void UnsortedType::UnsortedType()
{
length = 0;
}
bool UnsortedType::IsFull() const
{
return (length == MAX_ITEMS);
}
int UnsortedType::GetLength() const
{
return length;
}
NBA UnsortedType::GetItem(NBA customPlayer, bool& found)
{
bool moreToSearch;
int location = 0;
found = false;
moreToSearch = (location < length);
while (moreToSearch && !found)
{
switch (customPlayer.ComparedTo(info[location]))
{
case LESS :
case GREATER : location++;
moreToSearch = (location < length);
break;
case EQUAL : found = true;
item = info[location];
break;
}
}
return customPlayer;
}
void UnsortedType::MakeEmpty()
{
length = 0;
}
void UnsortedType::PutItem(NBA customPlayer)
{
info[length] = customPlayer;
length++;
}
void UnsortedType::DeleteItem(NBA customPlayer)
{
int location = 0;
while (customPlayer.ComparedTo(info[location]) != EQUAL)
location++;
info[location] = info[length - 1];
length--;
}
void UnsortedType::ResetList()
{
currentPos = -1;
}
NBA UnsortedType::GetNextItem()
{
currentPos++;
return info[currentPos];
}
UnsortedClass.h
#include "NBA.h"
class UnsortedClass //declares a class data type
{
public:
// 8 public member functions
void UnsortedType ( );
bool IsFull () const; //checks if list is full
int GetLength () const ; // returns length of list
NBA GetItem (NBA customPlayer, bool& found); //gets item specified in parameters
void PutItem (NBA customPlayer); //puts NBA player in list
void DeleteItem (NBA customPlayer); //deletes NBA player from list
void ResetList (); //resets list to 0
NBA GetNextItem (); //gets next item after current list position
private:
// 3 private data members
int length;
NBA info[MAX_ITEMS];
int currentPos;
};
NBA.h
#include <string>
using namespace std;
const int MAX_ITEMS = 10;
enum RelationType {LESS, GREATER, EQUAL};
class NBA {
private:
char firstInitial;
string lastName;
string team;
char position;
public:
void set_first_initial(char playerFirstInitial);
void set_last_name(string playerLastName);
void set_team(string teamName);
void set_position(char position);
char get_first_initial();
string get_last_name();
string get_team();
char get_position();
};
The errors I've been receiving are as follows (in picture format as I can't paste the lines without Stackoverflow interpreting it as code)

Constructors don't have a return type specified. Change
void UnsortedType::UnsortedType()
to
UnsortedType::UnsortedType()
Also the class name in its header declaration is wrong; everywhere else says UnsortedType but this says:
class UnsortedClass //declares a class data type

Related

Sorting function in a class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a class Client :
#include <stdio.h>
#include <iostream>
class Client
{
private:
vector<Liked*>like;
public:
Client();
~Client();
sort_id();
};
where like is a vector connection between class Client and Liked.
I created adding function:
void Client::addLiked(int id, string title)
{
Liked* newLiked= new Liked(id, title, year, minute, genre);
like.push_back(newLiked);
return ;
}
which is responsible for adding movie to the list. I would like to have sorting function, which will sort id in ascending order while printing the whole list :
void Client::print_Liked()
{
int n = like.size();
if(n == 0)
{
cout<<"Is empty"<<endl;
}
for(int i=0;i<n;i++)
{
sort_id();
like[i]->print_Liked();
}
}
I have tried with a bubble sort but I got errors :
void Client::sort_id()
{
int n = like.size();
bool swapped = true;
int j = 0;
int temp;
while (swapped) {
swapped = false;
j++;
for(int i = 0;i < n - j;++i)
{
if(like[i]->getID() > like[i+1]->getID())
{
temp = like[i]->getID();
like[i]->getID() = like[i+1]->getID();
array[i+1]->getID() = temp;
swapped = true;
}
}
}
}
The easiest way to sort your vector is by using the standard std::sort function together with a suitable lambda function for the comparisons.
Something like this:
void Client::sort_id()
{
std::sort(begin(like), end(like), [](Liked const* a, Liked const* b)
{
return a->getID() > b->getID();
});
}

c++ sudoku program using Back tracking, Segmentation fault (core dumped) ,all suggestions are welcomed [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
#include <iostream>
using namespace std;
//defining 9X9 grid.
int a[9][9] ={{0,0,3,0,9,2,6,0,0},
{1,0,0,3,0,0,8,0,0},
{0,0,5,0,1,0,0,4,0},
{0,3,0,0,0,0,2,5,8},
{2,4,0,0,5,0,0,0,0},
{0,0,0,6,2,0,0,0,3},
{0,1,4,0,0,9,0,3,0},
{6,0,0,7,0,0,1,0,0},
{3,0,0,0,0,4,0,0,2} };
// class sudoku.
class sudoku{
public:
int row,col,i,j,num;
//to check presence of element in particular row.
bool rowCheck(int a[9][9],int &row,int num)
{
for(j=0;j<9;j++)
{
if(a[row][j]==num)
return true;
}
return false;
}
//to check presence of element in particular column.
bool colCheck(int a[9][9], int &col, int num)
{
for(j=0;j<9;j++)
{
if(a[j][col]==num)
return true;
}
return false;
}
//to check presence of element in particular 3X3 grid.
bool boxCheck(int a[9][9],int &row ,int &col ,int num)
{
int x,y;
if(row<3)
x=0;
else if(row>=3 && row<6)
x=3;
else
x=6;
if(col<3)
int y=0;
else if(col>=3 && col<6)
y=3;
else
y=6;
for(i=x;i<x+3;i++)
{
for(j=y;j<y+3;j++)
{
if(a[i][j]==num)
return true;
}
}
return false;
}
//to check index which is unassigned.
bool unAssigned(int a[9][9],int &row,int &col)
{
for(row=0;row<9;row++)
{
for(col=0;col<9;col++)
{
if(a[row][col]==0){
return true;}
}
}
return false;
}
//to return true if position is suitable to insert .
bool isSafe(int a[9][9],int &row,int &col,int num)
{
if(!rowCheck(a,row,num) && !colCheck(a,col,num) &&
!boxCheck(a,row,col,num))
return true;
else
return false;
}
//function to solve sudoku.
bool sudokuSolver(int a[9][9])
{
if(!unAssigned(a,row,col))
return true;
for(i=1;i<=9;i++)
{
if(isSafe(a,row,col,i))
{
a[row][col]=i;
cout<<a[row][col];
if(sudokuSolver(a))
return true;
a[row][col]=0;
}
}
return false;
}
void display(int a[9][9])
{
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
//class ends
};
//main method
int main()
{
sudoku s;
s.sudokuSolver(a);
s.display(a);
return 0;
}
After calling: unAssigned(a,row,col) the value of row is 9 and the value of colis 9 when unAssigned() returns false. This is a consequence of using references to row and col.
bool unAssigned(int a[9][9],int &row,int &col)
{
for(row=0;row<9;row++)
{
for(col=0;col<9;col++)
{
if(a[row][col]==0){
return true;}
}
}
// here: row is 9 and col is 9
return false;
}
This means that you can return from sudokuSolver() with row and col out of bounds. This will trigger a segmentation fault in the following line:
if(sudokuSolver(a))
return true;
// here row or col are equal to 9 which is out of bounds
a[row][col]=0; // seg-fault here
You never initialize row and col which leads to undefined behaviour once you use their values.
Apart from that, I would suggest you to avoid hard coded array bounds and raw loops. If you use containers and iterators instead you can avoid out of bounds errors completely (not the problem here, but a line for(i=1;i<=9;i++) looks very suspicious and makes me think twice to realize that it is ok).
Moreover, dont pass by reference if the parameter is actually not modified by the method. E.g. bool colCheck(int a[9][9], int &col, int num) does not modify col, thus it is rather confusing why it takes col as reference. Also it is confusing that both row and col are members of the class but at the same time you pass them between the methods. I would suggest to rename the members to max_row and max_col, respectively.

Why is the insert function in linked list not working ? (C++) [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 6 years ago.
Improve this question
I'm working on a program that insert, delete accounts from a Bank.
Here is my .hpp code :
#ifndef DEF_BANK
#define DEF_BANK
#include <iostream>
using namespace std;
class Bank
{
private:
class _Account
{
public:
_Account(string, float);
string getClient();
float getBalance();
_Account *getNext();
void setClient(string);
void setBalance(float);
void setNext(Bank::_Account *);
private:
string _client; //nom client
float _balance; // stocke balance du compte
_Account *_next; // next account
};
_Account *_head;
public:
Bank();
Bank(string name, float balance);
_Account *rechercheClient(string);
float withdraw(string, float);
float deposit(string, float);
void createAccount(string, float);
void insert(string, float);
void remove(string name);
float deleteAccount(string);
void mergeAccounts(string, string);
void displayAccounts();
};
#endif
And here is my .cpp insert function:
void Bank::insert(string name, float balance)
{
_Account *temp(_head);
//_Account *n = new _Account(name, balance);
bool flag(true);
while(temp)
{
if (temp->getClient() == name)
{
/* code */
cout << "DENIED OPERATION! --> "<< name <<"’s account already exists." << endl;
flag = false;
}
temp = temp->getNext();
}
if (flag)
{
/* code */
temp->setNext(new _Account(name, balance));
}
}
Why when I try this in main.cpp:
int main()
{
Bank account_1;
account_1.insert("Hamza", 1000.0);
}
I get a segmentation fault :11 ? because I don't see my fault in the code.
bool flag(true);
while(temp)
{
if (temp->getClient() == name)
{
/* code */
cout << "DENIED OPERATION! --> "<< name <<"’s account already exists." << endl;
flag = false;
}
temp = temp->getNext();
}
if (flag)
{
/* code */
temp->setNext(new _Account(name, balance));
}
This doesn't make sense.
Control leaves the while loop once temp points to nullptr. Then you try to dereference that pointer with temp->setNext(new _Account(name, balance));. That's Undefined Behaviour.
As the other answer pointed out, your loop is wrong. If you change the last line from this:
temp = temp->getNext();
to this:
if (temp->getNext()) {
temp = temp->getNext();
} else {
break;
}
Then your loop should stop at the last element in the list instead of the (non existent) element after the last element in the list.
The real problem however is that your teacher thinks this is a good way to teach a beginner C++.

Beginning of an nQueens game in c++. Where is the error located in my code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I keep getting errors when trying to compile the following code. The error is
expected ',' or ';' before '{' token.
It says there's an error on the parentheses after the bool check_row(x)
If I comment it out the same happens for bool check_col(x).
I kept looking back at my books if I didn't define my functions properly but they seem correct, logically.
This is the beginning of an nQueens game on a 4x4 board.
The Queen is represented by the number 1.
The two boolean functions are to check if the row and columns are free.
startGame() assigns 0 to all boxes, and showBoard() shows results of the board.
#include <cstdlib>
#include <iostream>
using namespace std;
int x=0, y=0;
int square[4][4];
void startGame()
{
for(x=0;x<4;x++)
{
for(y=0;y<4;y++)
{
square[x][y]=0;
}
}
}
void showBoard()
{
for(int x=0;x<4;x++)
{
if(x!=0)
{
cout<<endl;
}
for(int y=0;y<4;y++)
{
cout<<square[x][y];
}
}
cout<<endl;
}
bool check_row(x)
{
for(y=0;y<4;y++)
{
if(square[x][y]==1)
{
return false;
}
else if(square[x][y]==0)
{
if(y==3)
{
return true;
}
continue;
}
}
}
bool check_col(y)
{
for(int x=0;x<4;x++)
{
if(square[x][y]==1)
{
return false;
}
else if(square[x][y]==0)
{
if(x==3)
{
return true;
}
continue;
}
}
}
int main(){
startGame();
showBoard();
return 0;
}
bool check_col(y) isn't a valid prototype. You need to provide a type for y - for example bool check_col(int y). The same applies to bool check_row(x).
you have to specify the datatype which you are passing as a parameter in your function..considering x and y are of int type and are local, your function prototype should be
bool check_row(int x)
bool check_col(int y)
If x and y are global then there is no need to pass them..simply
bool check_row()
bool check_col()
will work as the visibility of global variables will be throughout the program, unless shadowed

"segment fault" error after execute in c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
i have a problem with this codes. this program designed to use depth-first search in c++. i compiled it with Dev-Cpp , TurboC++ and visual studio .it compiled and the exe file have been made. but it make segment fault during execute. where is problem and what should i do ?
#include <stdio.h>
#include <string.h>
#include <iostream.h>
#include <vector.h>
#include <deque.h>
using namespace std;
//Structure for Adding Edge to Graph
struct Neighbor
{
string Name;
int Distance;
int ShortestDistance;
};
//Class Data Structure for City type Node:
class City
{
public:
string Name;
City( );
City(string);
vector<Neighbor> Neighbors;
vector<Neighbor>::iterator NeighborNumber;
void AddNeighbor (string, int);
};
//Parameterless Class constructor
City::City( )
{
Name="";
NeighborNumber=Neighbors.begin( );
}
//Class Constructor with Name supplied:
City::City(string CityName)
{
Name=CityName;
NeighborNumber=Neighbors.begin( );
}
//Function or Method to Add Connected Node to City data structure
void City::AddNeighbor(string NeighborName, int NeighborDistance)
{
Neighbor TempNeighbor;
TempNeighbor.Name=NeighborName;
TempNeighbor.Distance=NeighborDistance;
Neighbors.push_back(TempNeighbor);
NeighborNumber=Neighbors.begin( );
}
//Data Structure for Entire Map
vector<City> Cities;
void MakeMap()
{
City TempCity;
//Enter data for Arad
TempCity.Name="Arad";
TempCity.Neighbors.clear();
TempCity.AddNeighbor("Zerind",75);
TempCity.AddNeighbor("Sibiu", 140);
TempCity.AddNeighbor("Timisoara",118);
Cities.push_back(TempCity);
//Enter data for Bucharest
TempCity.Name="Bucharest";
TempCity.Neighbors.clear();
TempCity.AddNeighbor("Giurgiu",90);
TempCity.AddNeighbor("Urziceni",85);
TempCity.AddNeighbor("Fagaras",211);
TempCity.AddNeighbor("Pitesti",101);
Cities.push_back(TempCity);
}
//Function to Display contents of Cities data structure to screen:
void PrintCities()
{
City TempCity;
Neighbor TempNeighbor;
vector<City>::iterator CityNumber;
//Loop Through Entire Cities vector
for(CityNumber=Cities.begin();CityNumber<Cities.end();CityNumber++)
{
TempCity=*CityNumber;
cout<<"Current City: "<<TempCity.Name<<endl;
cout<<"Neighbors: ";
//Loop Through Each Neighbor printing name and distance
for(TempCity.NeighborNumber=TempCity.Neighbors.begin();
TempCity.NeighborNumber<TempCity.Neighbors.end();
TempCity.NeighborNumber++)
{
TempNeighbor=*TempCity.NeighborNumber;
cout<<" "<<TempNeighbor.Name;
cout<<","<<TempNeighbor.Distance;
}
cout<<endl<<endl;
}
}
//Function to return Success or Failure on finding the Child Node given the
//Parent is a structure of type Neighbor. The ChildCity is returned by reference.
bool GetChildCity(Neighbor Parent, City* ChildCity)
{
City TempCity;
vector<City>::iterator CityNumber;
for(CityNumber=Cities.begin();CityNumber<Cities.end();CityNumber++)
{
TempCity=*CityNumber;
if(TempCity.Name==Parent.Name)
{
*ChildCity=TempCity;
return true;
}
}
return false;
}
class PathRecord
{
public:
string AccumulatedPath;
string LastEntry;
int AccumulatedDistance;
PathRecord(string);
void AddPath(PathRecord, City, Neighbor);
};
PathRecord::PathRecord(string Start)
{
AccumulatedPath=Start;
LastEntry=Start;
AccumulatedDistance=0;
}
void PathRecord::AddPath(PathRecord ParentRecord, City ChildCity, Neighbor CurrentNeighbor)
{
this->AccumulatedPath=ParentRecord.AccumulatedPath+" - "+ChildCity.Name;
this->LastEntry=ChildCity.Name;
this->AccumulatedDistance=ParentRecord.AccumulatedDistance+CurrentNeighbor.Distance;
}
vector<PathRecord> PathsTraveled;
//Perform Depth First Search giving Start Location and Ending Location
bool DepthFirstSearch(string StartName, string EndName)
{
City CurrentCity;
City StartCity;
City ChildCity;
City ExploredCity;
City FrontierCity;
Neighbor CurrentNeighbor;
bool StartCityFound=false;
bool GoalFound=false;
bool AlreadyExplored;
bool AlreadyInFrontier;
bool NewChildFound;
bool PathFound;
vector<City>::iterator CityNumber;
deque<City> Frontier;
deque<City> Explored;
deque<City>::iterator FrontierCityNumber;
deque<City>::iterator ExploredCityNumber;
PathRecord NewRecord(StartName);
PathRecord TemporaryRecord("");
vector<PathRecord>::iterator PathNumber;
if(StartName==EndName) return true;
if(StartName=="" || EndName == "") return false;
//*************************************************************************
// Search For Start
//*************************************************************************
for(CityNumber=Cities.begin();CityNumber<Cities.end();CityNumber++)
{
CurrentCity=*CityNumber;
if(CurrentCity.Name==StartName)
{
StartCity=CurrentCity;
StartCityFound=true;
}
}
if(StartCityFound==false) return false;
PathsTraveled.push_back(NewRecord);
Frontier.push_back(StartCity);
//*************************************************************************
// Search For Goal
//*************************************************************************
cout<<"\nRecording Exploratory Process:\n"<<"Start Location: "<<
StartName<<"\t Ending Location: "<<EndName<<endl;
//Get Next Location in the Frontier
while(!Frontier.empty() && GoalFound==false)
{
CurrentCity=Frontier.back();
cout<<"\nCurrent City: "<<CurrentCity.Name<<endl;
NewChildFound=false;
//Look through the Neighbors until an explored City is found.
while(CurrentCity.NeighborNumber<CurrentCity.Neighbors.end() && NewChildFound==false)
{
CurrentNeighbor=*CurrentCity.NeighborNumber;
cout<<"Current Neighbor: "<<CurrentNeighbor.Name<<endl;
if(GetChildCity(CurrentNeighbor, &ChildCity)==false)
{
cout<<"Didn't find a child\n";
return false;
}
if(ChildCity.Name==EndName)
{
cout<<"Goal Found\n";
GoalFound=true;
}
//Check for Child Already Explored
AlreadyExplored=false;
ExploredCityNumber=Explored.begin();
while(AlreadyExplored==false && ExploredCityNumber<Explored.end())
{
ExploredCity=*ExploredCityNumber;
if(ExploredCity.Name==ChildCity.Name) AlreadyExplored=true;
ExploredCityNumber++;
}
//Check for Child Already in Frontier
if(AlreadyExplored==false)
{
AlreadyInFrontier=false;
FrontierCityNumber=Frontier.begin();
while(AlreadyInFrontier==false && FrontierCityNumber<Frontier.end())
{
FrontierCity=*FrontierCityNumber;
if(FrontierCity.Name==ChildCity.Name) AlreadyInFrontier=true;
FrontierCityNumber++;
}
}
//Put the parent in the Frontier queue and Expand the Child Node
//Record the process in the Paths Traveled vector.
if(AlreadyExplored==false && AlreadyInFrontier==false)
{
Frontier.push_back(ChildCity);
NewChildFound=true;
PathNumber=PathsTraveled.begin( );
PathFound=false;
while(PathFound==false && PathNumber<PathsTraveled.end( ))
{
TemporaryRecord=*PathNumber;
if(TemporaryRecord.LastEntry==CurrentCity.Name)
{
NewRecord.AddPath(TemporaryRecord,
ChildCity, CurrentNeighbor);
PathsTraveled.push_back(NewRecord);
PathFound=true;
}
PathNumber++;
}
}
CurrentCity.NeighborNumber++;
}
//Display the Explored Queue on each pass
if(NewChildFound==false)
{
Explored.push_back(CurrentCity);
Frontier.pop_back();
}
cout<<"Explored: ";
for(ExploredCityNumber=Explored.begin();
ExploredCityNumber<Explored.end();ExploredCityNumber++)
{
ExploredCity=*ExploredCityNumber;
cout<<ExploredCity.Name<<" \t";
}
cout<<endl;
//Display the Frontier Queue on each pass
cout<<"Frontier: ";
for(FrontierCityNumber=Frontier.begin();
FrontierCityNumber<Frontier.end();FrontierCityNumber++)
{
FrontierCity=*FrontierCityNumber;
cout<<FrontierCity.Name<<" \t";
}
cout<<endl;
}
return GoalFound;
}
//Goal Path will print the path used to locate the Goal
//Supply the name of the goal after a search has been successful
void PrintGoalPath(string GoalName)
{
vector<PathRecord>::iterator PathNumber;
PathRecord TemporaryRecord("");
cout<<"\nGoal Path: "<<endl;
for(PathNumber=PathsTraveled.begin();PathNumber<PathsTraveled.end();PathNumber++)
{
TemporaryRecord=*PathNumber;
if(TemporaryRecord.LastEntry==GoalName)
cout<<TemporaryRecord.AccumulatedPath
<<" "<<TemporaryRecord.AccumulatedDistance<<endl;
}
cout<<endl;
}
//Program Starts here:
int main()
{
bool GoalFound;
MakeMap();
string StartLocation="Arad";
string GoalState="Bucharest";
GoalFound=DepthFirstSearch(StartLocation, GoalState);
if(GoalFound) PrintGoalPath(GoalState);
else cout<<"Couldn't Do It - "<<GoalState<<" is nowhere to be found!!\n";
return 0;
}
Segment Fault means you have tried to access memory beyond the boundary of segment, maybe code or data segment.
The error is :
vector iterators incompatible
Why?
Because you have copied an Array from A to B, but you want to use A.begin() iterator to compare with B's iterator, and this will not pass compiler's compatibility check, in Visual Studio,
void _Compat(const _Myiter& _Right) const
{ // test for compatible iterator pair
if (this->_Getcont() == 0
|| this->_Getcont() != _Right._Getcont())
{ // report error
_DEBUG_ERROR("vector iterators incompatible");
_SCL_SECURE_INVALID_ARGUMENT;
}
}
So my advice is ,do not try to save the iterator that points to the vector begin, you can use a temporary iterator when need
And further advice, learn C++ systematically, do not write codes as you think unless you have enough confidence.
Come on, work hard, you can make it!