Unusual Declaration Error - c++

This seems like a really easy fix, but I can't understand what it's coming from.
Any help fully appreciated!
The following 2 lines of code produce the following errors respectively.
vector <spades::player> players(4, player());
vector <spades::card> deck(52,card());
error: 'player' was not declared in this scope
error: 'card' was not declared in this scope
Below is my card.cpp
#include <iostream>
#include <sys/ioctl.h>
#include <cstdio>
#include <unistd.h>
#include <locale.h>
#include <ncursesw/ncurses.h>
#include "card.h"
namespace spades {
card::card()
{
cardSuit = 0;
cardNum = 0;
}
card::card(int suit, int number)
{
cardSuit = suit;
cardNum = number;
}
}
Below is my player.cpp
#include <iostream> // Stream declarations
#include <vector> //Vectors used to store deck and players hands
#include <string> //String declarations
#include <algorithm> //Shuffle Method
#include <sys/ioctl.h>
#include <cstdio>
#include <unistd.h>
#include <locale.h>
#include <ncursesw/ncurses.h>
#include "player.h"
namespace spades {
using namespace std;
player::player() {
score =0; //total score
bid = NULL; //bid for that round
tricksTaken = 0; //score for thast round
sandBag = 0; //the number of points you win, more than what you bid, every 10th bag = -100
doubleNil = false;
for(int i=0; i<13; i++)
hand.push_back(card());
}
void player::addCard(spades::card b){
for (int i=0; i<hand.size(); i++){
//compare card being played to the ones in your hand to search and determine which one to erase
if((hand.at(i).getCardNum() == 0) &&
(hand.at(i).getSuit() == 0))
{
hand.at(i).setCardNum(b.getCardNum());
hand.at(i).setSuit(b.getSuit());
return;
}
}
}
void player::removeCard(spades::card a) {
for (int i=0; i<hand.size(); i++){
//compare card being played to the ones in your hand to search and determine which one to erase
if((hand.at(i).getCardNum() == a.getCardNum()) &&
(hand.at(i).getSuit() == a.getSuit()))
{
hand.at(i).setCardNum(0);
hand.at(i).setSuit(0);
return;
}
}
}
}

The compiler is actually complaining about the arguments you pass to vector constructors. You specified player() and card() in the constructor arguments, while it is obvious that your types are actually named spades::player and spades::card. You correctly specified the spades:: part in template parameters. Why did you omit the spades:: part from the constructor arguments?
It should be
vector <spades::player> players(4, spades::player());
vector <spades::card> deck(52, spades::card());
It should be noted though that the explicit argument is unnecessary, so you can just do
vector <spades::player> players(4);
vector <spades::card> deck(52);
and get the same result.

Also you don't need the
namespace spades {
}
block in player.cpp, only around you class definition in the header file.
Maybe you ment
using namespace spades;

Related

Check the presence of a number in an array with binary search

I have a test assessment that I need to do. There is one question that I have been having trouble with.
I have an array of numbers and I need to find a way to find that number in the array, which I have partially done. The problem becomes in the next step of the project which is that it has to accommodate a million items.
I believe this is binary search. How do I do a binary search or equivalent?
#include <iostream>
#include <sys/resource.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <algorithm>
#include <vector>
using namespace std;
class Answer
{
public:
static bool exists(int ints[], int size, int k)
{
for(int i=0; i<size; i++){
if(ints[i]<k){
return true;
}
}
return false;
}
};
The images below gives an idea of what I need and my code
What I need:
Why don't you just use standart lib function?
static bool exists(int ints[], int size, int k)
{
return std::binary_search(ints, ints + size, k);
}
I have already seen you got the answer, but it's never bad to implement binary search yourself, especially on the algorithm course, so may be it will help you to understand the algorithm:
static bool exists(const int ints[], int size, int k) {
int left = 0, right = size-1;
while(right-left>1) {
int middle = (right+left)/2;
if(ints[middle] > k) right = middle;
else left = middle;
}
if(ints[right] == k || ints[left] == k) return true;
return false;
}

returning a vector in get/set method

I am trying to use a get/set method in c++ for a vector. I keep getting an error throwing an instance of std::out_of_range which occurs when i try to cout the index value of ego_points.at(1) in my main code. I am providing my header file and my main code below but I'll try to explain here:
I have a class called Points with a public function called ScanCallback that builds the vector scannedData and uses the set function to set the private vector transmittedData equal to the scannedData. In my main code, I have an object called p1 of the Points class and I am trying to set a vector called ego_points equal to the transmittedData of object p1. I am able to build the vector ego_points by using the getVector() function but cannot access it's data. Anyone know why not?
Header File:
#pragma once
#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include "iostream"
#include "string"
#include "motor_driver/Motor_speeds.h"
#include "motor_driver/cartesian.h"
#include <vector>
#ifndef MOTOR_DRIVER_H
#define MOTOR_DRIVER_H
using namespace std;
using namespace motor_driver;
class Points {
public:
vector<float> scannedData;
int i;
int size;
int size1;
int size2;
Points() : scannedData(0) {} //Must match the class name. This is the constructor.
void set(vector<float> transmittingData){
transmittedData = transmittingData;
}
void ScanCallback(const sensor_msgs::LaserScan::ConstPtr& scan) {
scannedData.clear();
size = scan->ranges.size();
scannedData.resize(size);
for(i = 0; i < size; i = i + 1){
scannedData.at(i) = scan->ranges[i];
}
set(scannedData);
}
int getSize(){
return size;
}
vector<float> getVector(){
return transmittedData;
}
private:
vector<float> transmittedData;
};
#endif
Main Code:
#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include "iostream"
#include "string"
#include "motor_driver/Motor_speeds.h"
#include "motor_driver/cartesian.h"
#include <motor_driver.h>
#include <vector>
using namespace std;
using namespace motor_driver;
Points p1;
int main(int argc, char** argv) {
ros::init(argc, argv, "motor_driver_node");
ros::NodeHandle nh;
ros::Subscriber sub;
ros::Rate r(1);
int ss;
int newsize;
int index;
vector<float> ego_points;
while (ros::ok()) {
sub = nh.subscribe<sensor_msgs::LaserScan>("/scan",10, &Points::ScanCallback, &p1);
newsize = p1.getSize();
ego_points.clear();
ego_points.resize(newsize);
ego_points = p1.getVector();
cout << ego_points.at(1) << endl;
r.sleep();
ros::spinOnce();
}
return 0;
}
My error:
:~/Desktop/Naes_Thesis$ rosrun motor_driver motor_driver_node
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
Aborted (core dumped)
does the vector have at least two elements? If you want to access the first element you should use:
cout << ego_points.at(0) << endl;
Also the size method is probably incorrect. It should be something like this:
int getSize() const {
return transmittedData.size();
}
Otherwise the size may contain a different value than the actual vector size
Actually I figured it out. The issue was that the size of the vector is 0 until the vector is built. So I added a if (vector =0) then (do nothing) portion to the code and it fixed it. Thank you Noel-lopes and 1201ProgramAlarm for your contribution.

error: no matching function for call to "Queue::Queue()"

So I am trying to call a function in my main.cpp file but I get "error: no matching function for call to 'Queue::Queue()."
Queue.h
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
class Queue
{
public:
Queue(int);
~Queue();
//circular queue methods
void enqueue(std::string);
std::string dequeue(); //should send through network, call transmit msg
void printQueue();
bool queueIsFull(); //send when full
bool queueIsEmpty(); //send when empty
protected:
private:
int queueSize;
int queueHead;
int queueTail;
int queueCount;
std::string *arrayQueue;
};
#endif // QUEUE_H
Queue.cpp
#include "Queue.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
Queue::Queue(int qs)
{
queueSize = qs;
arrayQueue = new string[queueSize];
queueHead = 0;
queueTail = 0;
}
Queue::~Queue()
{
delete[] arrayQueue;
}
void Queue::enqueue(string word)
{
for (int i=0;i<10;i++)
{
arrayQueue[i] = word;
}
}
void Queue::printQueue()
{
for(int j=0;j<10;j++)
{
cout<<arrayQueue[j]<<endl;
}
}
main.cpp
#include <iostream>
#include "Queue.h"
using namespace std;
int main()
{
int userChoice;
Queue q;
while(2==2)
{
cout<<"======Main Menu======"<<endl;
cout<<"1. Enqueue word"<<endl;
cout<<"2. Dequeue word"<<endl;
cout<<"3. Print queue"<<endl;
cout<<"4. Enqueue sentence"<<endl;
cout<<"5. Quit"<<endl;
cin>>userChoice;
if (userChoice == 1)
{
string enqueueWord;
cout<<"word: ";
cin>>enqueueWord;
enqueue(enqueueWord);
}
if (userChoice == 2)
{
}
if (userChoice == 3)
{
}
if (userChoice == 4)
{
}
if (userChoice == 5)
{
}
}
return 0;
}
So to call the function from the header file I did "Queue q;" at the beginning of the int main() and then when I needed to call the function I did "q.enqueue(enqueueWord)." I also tried just doing "Queue::enqueue(enqueueWord), but that also didn't work and I get a different error. I feel like this is an easy fix but I just can't figure it out. Thanks for the help and feel free to ask me to clarify anything.
Queue q;
attempts to call the default constructor Queue::Queue. However, this constructor has been removed automatically since you explicitly declare a constructor, namely Queue::Queue(int), on your own.
Pass an appropriate argument to q when initialized, like
Queue q1(42); // pre-C++11 syntax
Queue q{42}; // available since C++11
(Note: 42 is only an exemplary value here.)
You could also use default arguments to keep the definition as-is and initialize the object with a default value.
Notes:
Why while(2==2)? while (true) is the common way.

C++ ~ call to function in client gives error: "identifier ____ is undefined"

I'm coming to you with a problem that has several different files involved. I'm not sure why I'm getting the error specified in the title. Let me put the files below and go from there.
DummyClient.cpp
#include "Gameboard.h" //for Gameboard
#include "Location.h" //for function prototypes
#include "zList.h" //for Zombies
#include <iostream> //for input/output stream
using namespace std;
void main()
{
srand(123456789);
Gameboard myGB;
myGB = Gameboard();
ZombieListClass();
ZombieRec zombieList[MAX_ZOMBIES];
PopulateZombies(zombieList[MAX_ZOMBIES]); // this throws the error here of "Error: identifier "PopulateZombies" is undefined"
}
zList.h
#ifndef ZLIST_H
#define ZLIST_H
#include "Location.h" // for list record
#include "ZombieRec.h"
#include "Gameboard.h"
class ZombieListClass
{
public:
ZombieListClass(); //default constructor
void PopulateZombies(ZombieRec zombieList[]);
bool IsInBounds(int row, int col);
private:
ZombieRec list[MAX_ZOMBIES]; //stores the items in the list
int length; //# of values currently in the list
int currPos; //position of current element
int strength; // health and attack units of a zombie
};
#endif
zList.cpp
#include "zList.h"
ZombieListClass::ZombieListClass() //default constructor
{
length = 0;
currPos = 0;
strength = 5;
LocationRec zombieLoc;
}
void ZombieListClass::PopulateZombies(ZombieRec zombieList[])
{
int row, col;
for (int i = 0; i < MAX_ZOMBIES; i++)
{
row = rand() % MAX_ROW + 1;
col = rand() % MAX_COL + 1;
while (!IsInBounds(row, col))
{
row = rand() % MAX_ROW + 1;
col = rand() % MAX_COL + 1;
}
zombieList[i].currLoc.row = row;
zombieList[i].currLoc.col = col;
}
}
bool ZombieListClass::IsInBounds(int row, int col)
{
if (row == 0 || row == MAX_ROW + 1 || col == 0 || col == MAX_COL + 1)
{
return false;
}
else
{
return true;
}
}
Gameboard.h
#ifndef GAMEBOARD_H
#define GAMEBOARD_H
#include "Location.h"
#include "ZombieRec.h"
#include "zList.h"
const int MAX_ROW = 3; // total number of rows in the board
const int MAX_COL = 3; // total number of cols in the board
class Gameboard
{
public:
Gameboard();
private:
int boardSizeArr[MAX_ROW + 2][MAX_COL + 2];
}; // end Gameboard
#endif
and finally, Gameboard.cpp
#include "Gameboard.h"
Gameboard::Gameboard()
{
// Declares a board with a boundary along the outside
boardSizeArr[MAX_ROW + 2][MAX_COL + 2];
}
I'm not looking to be spoonfed and for somebody to solve my problem for me, I'm trying to figure out what I'm doing wrong so that the remainder of my project isn't as bumpy as it has been this whole time.
Looking back on my error, "identifer "PopulateZombies" is undefined", I can't imagine why it is. Could this have something to do with the scope of how I'm doing things? If I've left any code out (I didn't put everything in there but I think I have everything relevant) just let me know, I'm able to converse back and forth as long as this takes.
Thank you to everybody in advance that tries to help :)
-Anthony
In general, you call the function using a variable, instead of calling it directly if defined in a class:
ZombieListClass zombieList=new ZombieListClass(); // add a variable here
ZombieRec zombieList[MAX_ZOMBIES];
zombieList.PopulateZombies(zombieList[MAX_ZOMBIES]); // See the difference?
I am not sure whether the error you posted is the only error. Here is what I see in your main.cpp
#include "Gameboard.h" //for Gameboard
#include "Location.h" //for function prototypes
#include "zList.h" //for Zombies
#include <iostream> //for input/output stream
using namespace std;
void main()
{
srand(123456789);
Gameboard myGB;
myGB = Gameboard();//The constructor"Gameboard()" is automatically called when you defined
//myGB in the previous line,
ZombieListClass();//see Hai Bi's great answer on this one
ZombieRec zombieList[MAX_ZOMBIES];//ZombieRec is a member of ZombieListClass, use . to access it
PopulateZombies(zombieList[MAX_ZOMBIES]); //Also see Hai Bi's answer
}
My advice is to revisit the concept of constructor and class definition before put your hands on s a problem like this.

Pointer declaration in .h, instantiation in .cpp but unresolved in other project files

I am trying to declare an array of pointers to my Node class/object in a header file and then in the constructor for the class I want to instantiate the size of the array. I then wish to initialize the array with Node object.
The problems that I am having have to do with correct syntax when first declaring the Node array in the SOM.h file. I have tried just having it be a Node* nodeArray and Node* nodeArray[][some constant number]. Not sure if either or both of these are a correct way to do this.
Then in the SOM.cpp constructor I am initializing this this way nodeArray = Node[Config::NODE_GRID_HEIGHT][Config::NODE_GRID_WIDTH]
I then run an initializing function for the array of node pointers
void SOM::RandInitilizeNodeArray(){
srand (time(NULL));
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
nodeArray[i][j] = new Node();
nodeArray[i][j]->modelVec[0] = (rand() % 256)/255;//there is a uniform real distribution that gives better results
nodeArray[i][j]->modelVec[1] = (rand() % 256)/255;//THE 256 HERE MIGHT NEED TO BE 255
nodeArray[i][j]->modelVec[2] = (rand() % 256)/255;
}
}
}
For each of the 3 times I try to access the modelVec I get "Field "modelVec" could not be resolved" from eclipse. Why? Am I not declaring the array of pointers correctly, not initializing correctly, not accessing correctly. Maybe eclipse just hates me.
Here is more code to look at.
SOM.h
#ifndef SOM_H
#define SOM_H
#include "Node.h"
#include "LoadFile.h"
//#include "LearningFunc.h"
#include "Config.h"
#include <cstdlib>
#include <string>
#include "opencv2/core/core.hpp"
#include <vector>
#include <iostream>
#include <stdio.h>
#include <opencv2/highgui/highgui.hpp>//FOR TESTING
//#include <highgui.h>
class SOM{
public:
// Variables
Node* nodeArray;//[][Config::NODE_GRID_WIDTH];
//Node* nodeArray;
cv::Mat inputImg;
cv::Mat normalizedInputImg;
std::string filename;
cv::Mat unnormalizedInputImg;//FOR TESTING
cv::Mat outputImg;
//LearningFunc thislearner();
// Functions
//Node* FindWinner(std::vector<uchar>);//send in a pixel vector get a winning node in return
void BatchFindWinner();
Node* SingleFindWinner(uchar*);
void NormilizeInput();
void InitilizeNodeArray();
void RandInitilizeNodeArray();
float GetSimilarity(uchar*, uchar*);
void AllocateNodeArray();
void OutputNodeArray();
void UnnormalizeInputImage();
void DisplayWins();
cv::Mat OutputSom();
void MyPause(std::string);//FOR TESTING
void WriteSomToDisk(std::string);
// Constructors
SOM(){};
SOM(std::string);
~SOM(){};
private:
};
#endif // SOM_H
SOM.cpp
SOM::SOM(std::string file){
filename = file;
inputImg = LoadFile(filename);
nodeArray = Node[Config::NODE_GRID_HEIGHT][Config::NODE_GRID_WIDTH];
//nodeArray = new Node[NODE_GRID_HEIGHT][NODE_GRID_WIDTH];
AllocateNodeArray();
InitilizeNodeArray();
//OutputNodeArray();//FOR TESTING
}
void SOM::RandInitilizeNodeArray(){
srand (time(NULL));
for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
nodeArray[i][j] = new Node();
nodeArray[i][j]->modelVec[0] = (rand() % 256)/255;//there is a uniform real distribution that gives better results
nodeArray[i][j]->modelVec[1] = (rand() % 256)/255;//THE 256 HERE MIGHT NEED TO BE 255
nodeArray[i][j]->modelVec[2] = (rand() % 256)/255;
}
}
}
Node.h
#ifndef NODE_H
#define NODE_H
#include <vector>
#include "Config.h"
class Node{
public:
//variables
//unsigned int location[2];//location of node in 2d grid
std::vector<unsigned int> winnerDataPixels;
uchar* modelVec;
//functions
//constructors
Node();
~Node(){};
private:
};
#endif //node.h end define
Node.cpp
#include "Node.h"
#include "Config.h"
Node::Node(){
modelVec = uchar[Config::vectorLength];
}