I am trying to create a vector of objects but i have some issues. I can't push_back over 19 objects to my vector because it shows up an error message of bad_alloc.
I try to resize my vector with resize() or reserve() but still nothing.
For resize(), I read that you need to provide 2 arguments to resize a vector.But still nothing.
When I try to use it without push_back it shows error: expected primary-expression before ')' token.
#define N 10 //ari8mos seirwn tou xarth
#define M 10 //ari8mos sthlwn tou xarth
#define TREAS 100//posothta 8usaurou
#define PORTS 100//ari8mos limaniwn
extern void ships(map (&myArray)[N][M], vector<ship> &myShips);
void ships(map (&myArray)[N][M], vector<ship> &myShips)
{
int i,j,y;
srand ( time(NULL) );
//myShips.reserve(21);
//myShips.resize(20,ship);
cout << myShips.capacity() << endl;
int x=0;
for( i = 0; i <19 ; i++){
myShips.push_back(pirate(rand() % N,rand() % M,100,100,100,1,'#',myArray,myShips));
}
for( i=0;i<myShips.size();i++ ){
cout << myShips[i].get_symbol() << " ";
}
}
here is the rest of code to help you understand:
class ship
{
protected:
int i,j,x2,y2;
//vector<vector<map> > myArray;
//ship (&myShips)[N][M];
int x;
int y;
map (myArray)[N][M];
vector<ship> myShips;
int max_resistance;
int current_resistance;
int speed;
int reserve_treasure;
char symbol;
public:
ship(int x_, int y_, int max_res, int cur_res, int res_treas, int sp, char sy, map (&myArr)[N] [M], vector<ship> &Ship)
:x(x_)
,y(y_)
,max_resistance(max_res)
,current_resistance(cur_res)
,reserve_treasure(res_treas)
,speed(sp)
,symbol(sy)
,myArray(myArr)
,myShips(Ship)
{cout << "eimai o 'ship' 2" << endl; }
~ship() {}
int get_x();
int get_y();
float get_max_resistance();
float get_current_resistance();
int get_speed();
float get_reserve_treasure();
char get_symbol();
void set_x(int pos_x);
void set_y(int pos_y);
void set_max_resistance(float maxres);
void set_current_resistance(float curres);
void set_speed(int sp);
void set_reserve_treasure(float restrea);
void set_symbol(char sy);
void movement();
void operation();
};
int ship::get_x(){
return x;
}
int ship::get_y(){
return y;
}
float ship::get_max_resistance(){
return max_resistance;
}
float ship::get_current_resistance(){
return current_resistance;
}
int ship::get_speed(){
return speed;
}
float ship::get_reserve_treasure(){
return reserve_treasure;
}
char ship::get_symbol(){
return symbol;
}
void ship::set_x(int pos_x){
x = pos_x;
}
void ship::set_y(int pos_y){
y = pos_y;
}
void ship::set_max_resistance(float maxres){
max_resistance = maxres;
}
void ship::set_speed(int sp){
speed = sp;
}
void ship::set_current_resistance(float curres){
current_resistance = curres;
}
void ship::set_reserve_treasure(float restrea){
reserve_treasure = restrea;
}
void ship::set_symbol(char sy){
symbol = sy;
}
class pirate : public ship
{
public:
pirate(int posx, int posy, float mr, float cr, float rt, int spe, char sym, map (&Array)[N] [M],vector<ship> &Ship ):ship(posx,posy,mr,cr,rt,spe,sym,Array,Ship){
cout << "eimai o 'pirate' 1" << endl;
// ship(90,90,1,50,'#',Array,Ship) {//vector<vector<map> > Array, vector<vector<ship> > Ship) {}
};
Hope you can help
Looking through this code, did you create a custom definition for map? Otherwise, if you are trying to create an [N][M] array of Map objects, you are missing the type declaration of map. e.g. map<int,string>
If you are trying to use map as a multidimensional array, this is not what std::map is for. Map is a generic container for storing key/value pairs.
Related
might be a stupid question and if it is, let me know, I will delete it as soon as possible. The thing is I have to make a deep copy in class "Kambarys" (ignore mixed languages, I know I shouldn't do that). Program terminates after trying to call function second time. Probably the problem is my syntax in constructor copy, but I can't find the correct one anywhere. One of the requirements is to create langas, durys and kambarys in dynamic memory using "new" and delete windows vector and door in Kambarys destructor. Appreciate the help!
Requirements:
In the main method, use the new operator to create room k1, add windows and doors to it. Write a constructor Room (const Room & k) that would create a correct copy. In the method main, write another room k2. Calculate the length of the baseboards / wall area.
Perform the following steps: k2 = * k1; delete k1;
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
class Langas{
private:
float height;
float widht;
static int countL;
public:
Langas(float h, float w){
this->height=h;
this->widht=w;
countL++;
}
~Langas(){
--countL;
}
float getHeight(){
return height;
}
float getWidht(){
return widht;
}
static int getWindowCount(){
return countL;
}
};
class Durys{
private:
float heightD;
float widhtD;
static int countD;
public:
Durys(float hD, float wD){
this->heightD=hD;
this->widhtD=wD;
countD++;
}
~Durys(){
--countD;
}
float getHeightD(){
return heightD;
}
float getWidhtD(){
return widhtD;
}
static int getDoorCount(){
return countD;
}
};
class Kambarys{
private:
float heightK;
float widhtK;
float lenghtK;
public:
vector<Langas*> windows;
Durys* door;
Kambarys(float hK, float wK, float lK){
this->heightK=hK;
this->widhtK=wK;
this->lenghtK=lK;
}
Kambarys(const Kambarys &k){
this->door=k.door;
this->windows=k.windows;
heightK=k.heightK;
widhtK=k.widhtK;
lenghtK=k.lenghtK;
}
~Kambarys(){
door=NULL;
for(int i=0; i<windows.size(); i++){
delete windows[i];
}
windows.clear();
delete door;
}
float getHeightK(){
return heightK;
}
float getWidhtK(){
return widhtK;
}
float getLenghtK(){
return lenghtK;
}
void addWindow(Langas* w){
windows.push_back(w);
}
void addDoor(Durys *d){
door=d;
}
};
float countWallPlot(Kambarys* k){
float cWPlot=(2*k->getLenghtK()*k->getHeightK())+(2*k->getWidhtK()*k->getHeightK());
for(int i=0; i<k->windows.size(); i++){
cWPlot-=((k->windows[i]->getHeight()))*(k->windows[i]->getWidht());
}
cWPlot-=((k->door->getHeightD()))*(k->door->getWidhtD());
return cWPlot;
}
float countLenght(Kambarys* k){
float floorL=(k->getLenghtK()*k->getWidhtK()*2);
floorL-=(k->door->getWidhtD());
return floorL;
}
int Langas::countL=0;
int Durys::countD=0;
int main(){
Langas *langas1=new Langas(3.4, 1.2);
Durys *durys=new Durys(3.1, 1.5);
Langas *langas2=new Langas(6.4, 1.5);
Kambarys *k=new Kambarys(30.4, 40.1, 50.1);
Kambarys *k2=k;
k->addWindow(langas1);
k->addWindow(langas2);
k->addDoor(durys);
cout<<countWallPlot(k)<<" "<<countLenght(k)<<endl;
cout<<"Window count "<<Langas::getWindowCount()<<", door count "<<Durys::getDoorCount()<<endl;
k2=k;
delete k;
cout<<countWallPlot(k2)<<" "<<countLenght(k2)<<endl;
cout<<"Window count "<<Langas::getWindowCount()<<", door count "<<Durys::getDoorCount()<<endl;
}
You have to allocate memory for k2 and copy the object, not the pointer.
You have to allocate memory in the copy constructor and copy assignment operator.
door=NULL; before delete door; would skip the delete and cause a memory leak.
windows.clear(); is not necessary in the destructor. Keep your code simple.
EDIT: After you added "Perform the following steps: k2 = * k1; delete k1;" I made k2 an object, not a pointer.
#include <iostream>
#include <vector>
class Langas {
private:
float height;
float width;
static int count;
public:
Langas(float h, float w): height(h), width(w) {
++count;
}
~Langas() { --count; }
float getHeight() const { return height; }
float getWidht() const { return width; }
static int getWindowCount() { return count; }
};
class Durys {
private:
float height;
float width;
static int count;
public:
Durys(float h, float w): height(h), width(w) {
++count;
}
~Durys() { --count; }
float getHeight() const { return height; }
float getWidth() const { return width; }
static int getDoorCount() { return count; }
};
class Kambarys {
private:
float height;
float width;
float length;
public:
std::vector<Langas *> windows;
Durys *door = nullptr;
Kambarys(float hK, float wK, float lK): height(hK), width(wK), length(lK) {}
Kambarys(const Kambarys &k): height(k.height), width(k.width), length(k.length), windows(), door(k.door ? new Durys(k.door->getHeight(), k.door->getWidth()) : nullptr) {
for (const auto window : k.windows) {
windows.emplace_back(new Langas(window->getHeight(), window->getWidht()));
}
}
Kambarys &operator=(const Kambarys &k) {
door = k.door ? new Durys(k.door->getHeight(), k.door->getWidth()) : nullptr;
for (const auto window : k.windows) {
windows.emplace_back(new Langas(window->getHeight(), window->getWidht()));
}
height = k.height;
width = k.width;
length = k.length;
return *this;
}
~Kambarys() {
for (auto window : windows) {
delete window;
}
delete door;
}
float getHeight() const { return height; }
float getWidth() const { return width; }
float getLength() const { return length; }
void addWindow(Langas *w) { windows.emplace_back(w); }
void addDoor(Durys *d) { door = d; }
};
float countWallPlot(const Kambarys &k) {
float cWPlot = 2 * k.getLength() * k.getHeight() + 2 * k.getWidth() * k.getHeight();
for (const auto window : k.windows) {
cWPlot -= window->getHeight() * window->getWidht();
}
cWPlot -= k.door->getHeight() * k.door->getWidth();
return cWPlot;
}
float countLength(const Kambarys &k) {
float floor = k.getLength() * k.getWidth() * 2;
floor -= k.door->getWidth();
return floor;
}
int Langas::count = 0;
int Durys::count = 0;
int main() {
Langas *langas1 = new Langas(3.4, 1.2);
Durys *durys = new Durys(3.1, 1.5);
Langas *langas2 = new Langas(6.4, 1.5);
Kambarys *k = new Kambarys(30.4, 40.1, 50.1);
Kambarys k2(*k);
k->addWindow(langas1);
k->addWindow(langas2);
k->addDoor(durys);
std::cout << countWallPlot(*k) << " " << countLength(*k) << std::endl;
k2 = *k;
std::cout << "Window count " << Langas::getWindowCount() << ", door count " << Durys::getDoorCount() << std::endl;
delete k;
std::cout << countWallPlot(k2) << " " << countLength(k2) << std::endl;
std::cout << "Window count " << Langas::getWindowCount() << ", door count " << Durys::getDoorCount() << std::endl;
}
Im having trouble writing my main for a class I created. I created a class called CartesianPoints which I want to use to construct my main with. I have the general structure of my main created but am struggling with the some technical stuff..
Heres what im looking for:
creating an empty vector of CartesianPoint Objects which will be the starting point for the vector
Limit range for x and y values between 10 & -10.
loop to show user the points they just entered and ask what they would like to enter next
the loop above should continue until the break is triggered
here is my header for CartesianPoints
#ifndef MY_CARTESIAN_POINT_H
#define MY_CARTESIAN_POINT_H
#include <iostream> // cin, cout
#include <sstream> // stringstream
#include <cmath> // sqrt()
#include <limits> // INT_MAX
#include <stdexcept> // out_of_range
using namespace std;
class CartesianPoint
{
public:
CartesianPoint(int x = 1, int y = 1) { SetPoint(x, y); }
int GetX() const { return myX; }
int GetY() const { return myY; }
double GetDistanceTo(CartesianPoint pointTo) const;
string ToString() const;
void SetX(int x) { myX = validateCoordinateValue(x); }
void SetY(int y) { myY = validateCoordinateValue(y); }
void SetPoint(int x, int y) { SetX(x); SetY(y); }
static int GetLimit() { return sharedLimit; }
static void SetLimit(int limit) { sharedLimit = abs(limit); }
private:
int myX;
int myY;
static int sharedLimit;
int validateCoordinateValue(int value) const;
};
int CartesianPoint::sharedLimit = INT_MAX;
double CartesianPoint::GetDistanceTo(CartesianPoint pointTo) const
{
int xDelta = pointTo.myX - myX;
int yDelta = pointTo.myY - myY;
return sqrt((xDelta * xDelta) + (yDelta * yDelta));
}
string CartesianPoint::ToString() const
{
stringstream strOut;
strOut << "(" << myX << ", " << myY << ")";
return strOut.str();
}
int CartesianPoint::validateCoordinateValue(int value) const
{
if((value < -sharedLimit || value > sharedLimit))
{
throw out_of_range( "Parameter (" + to_string(value) + ") must be between "
+ to_string(-sharedLimit) + " and " + to_string(sharedLimit) + ".");
}
return value;
}
#endif
here is my main so far
int main()
{
GreetingScreen(); // just a formatting function ive already created
// while loop that makes will give the option to end the program.
while(/* if myX! =10 and myY!= 10 keep doing this loop */ )
{
// try catch for errors....
try
{
cout << "Move from point" /* (0,0)*/ "to where?" << endl;
cout << "X: " << endl;
cin >> x; //point x
cout << "Y: " << endl;
cin >> y; //point y
catch
{
cerr << "could not do this task";
}
}
} // ending of while loop
} // ending of main
You are on the right path, but there are a few things that I do see a concern with.
In your class I don't see where you are using <iostream> I think you can omit it.
You are using using namespace std. It is preferred to just scope out the namespace std::.
About your constructor:
CartesianPoint(int x = 1, int y = 1) { SetPoint(x, y); }
Here you have two default values, there are two options here:
Declare this constructor as explicit
explicit CartesianPoint( int x = 1, int y = 1 ) { SetPoint( x, y ); }
Declare a default and user defined constructors
CartesianPoint() { SetPoint( x, y ); }
CartesianPoint( int x, int y ) { SetPoint( x, y ); } // by value
CartesianPoint( int& x, int& y ) { SetPoint( x, y ); } // by reference
Note - The third constructor my require overloads for the SetPoint function to accept by reference, however if you continue reading below you will see what I've done with your class.
Personally I think the 2nd choice is the better of the two. If you choose to use a constructor with 2 parameters and both have default values and you are not declaring the constructor as explicit; you will run into trouble.
This is why I preferably choose to use the 2nd option of declaring both a default constructor and a user defined constructor. This gives you the flexibility to do any of the following:
{
CartesianPoint p1; // default constructor called
CartesianPoint p2( 5, 6 ); // user defined constructor called.
int x = 5;
int y = 6;
CartesianPoint p3( x, y ); // another user defined constructor called.
}
Now there is something else with the constructor: you are calling a member function to set the point (x,y) This is not really needed. Class's have a member initializer list; use them! You are also using member functions SetX() and SetY() in your member function SetPoint() the extra calls are not needed.
Personally I would write your class as such:
#ifndef MY_CARTESIAN_POINT_H
#define MY_CARTESIAN_POINT_H
// #include <iostream> // cin, cout
#include <sstream> // stringstream
#include <cmath> // sqrt()
#include <limits> // INT_MAX
#include <stdexcept> // out_of_range
// using namespace std;
class CartesianPoint {
private:
int myX;
int myY;
static int sharedLimit;
public:
CartesianPoint() : myX( 0 ), myY( 0 ) {} // I chose 0, but you can choose any default values for (x,y)
CartesianPoint( int x, int y ) :
myX( validate( x ) ),
myY( validate( y ) ) {
}
CartesianPoint( int& x, int& y ) :
myX( validate( x ) ),
myY( validate( y ) ) {
}
int GetX() const { return myX; }
int GetY() const { return myY; }
// by value
void SetX(int x) { myX = validate(x); }
void SetY(int y) { myY = validate(y); }
void SetPoint(int x, int y) {
myX = validate( x );
myY = validate( y );
}
// by reference
void SetX( int& x ) { myX = validate(x); }
void SetY( int& y ) { myX = validate(y); }
void SetPoint( int& x, int& y ) {
myX = validate( x );
myY = validate( y );
}
double GetDistanceTo(CartesianPoint pointTo) const;
string ToString() const;
static int GetLimit() { return sharedLimit; }
static void SetLimit(int limit) { sharedLimit = abs(limit); }
private:
int validate( int value ) const; // by value
int validate( int& value ) const; // by reference
};
int CartesianPoint::sharedLimit = INT_MAX;
double CartesianPoint::GetDistanceTo(CartesianPoint& pointTo) const {
int xDelta = pointTo.myX - myX;
int yDelta = pointTo.myY - myY;
return sqrt((xDelta * xDelta) + (yDelta * yDelta));
}
std::string CartesianPoint::ToString() const {
std::stringstream strOut;
strOut << "(" << myX << ", " << myY << ")";
return strOut.str();
}
int CartesianPoint::validate(int value) const {
return validate( value );
}
int CartesianPoint::validate( int& value ) const {
if((value < -sharedLimit || value > sharedLimit)) {
std::ostringstream stream;
stream << "Out Of Range: Parameter ("
<< + ToString(value)
<< + ") must be between "
<< + ToString(-sharedLimit)
<< + " and "
<< + ToString(sharedLimit)
<< + '.';
throw stream.str();
}
return value;
}
#endif
main.cpp
#include <iostream>
#include "CartesianPoint.h"
int main() {
try {
std::vector<CartesianPoint> points; // It's already empty
while( condition(s) ) {
// do work
}
} catch( std::string& str ) {
std::cout << str << std::endl;
return -1;
} catch( ... ) {
std::cout << "Caught some other or unknown exception." << std::endl;
return -1;
}
return 0;
}
EDIT - I made a change to the validateCoordinateValue I first changed it's name to just validate for several reasons:
1st: It is a private method to the function and it isn't exposed as part of its public interface.
2nd: It is shorter and easier to type as well as read.
3rd: When using it in the class just as validate() it is already self explanatory of what the function does. Compare the two:
myX = validateCoordinateValue( x );
myX = validate( x );
Then I also added in an overload of the function to accept pass by reference as well. The reference version does the work, the pass by value function just simply returns and calls the reference version.
I'd like to access to a double pointer which is located in another class "Board".
class Board
{
public:
Board(void);
Board(unsigned int xSize, unsigned int ySize);
~Board(void);
void SetObjectManager(ObjectManager* pObm);
void SetBlock(Block* block);
void LoadBoard(void);
void InitBoard(void);
//Other Functions...
private:
ObjectManager* m_obm;
Block* m_block;
//pointer to pointer to a int. (for 2 dimensional-array)
int **m_board;
};
First, the Board class. at the last line of class, you can see m_board.
I want to change this value in outside of this class.
Like this,
void Block::InitBlock(void)
{
int randPiece = Random::GIRand().RandInt(0, 1);
int randPos = Random::GIRand().RandInt(0, 10);
switch (randPiece)
{
case 0:
m_piece[2][1] = 1;
m_piece[2][2] = 1;
m_piece[2][3] = 1;
m_piece[3][3] = 1;
break;
//Other cases are here...
}
std::cout << "RandPos : " << randPos << std::endl;
std::cout << "RandPiece : " << randPiece << std::endl;
for (int y = 0; y < m_ySize; ++y)
{
for (int x = 0, pX = randPos; x < m_xSize; ++x, ++randPos)
{
if (m_piece[x][y] != 0)
m_board->SetBoardStatus(randPos, y, 1);
}
}
}
But, When I run this program, It blows up at SetBoardStatus(int, int, int)
SetBoardStatus looks like this,
void Board::SetBoardStatus(int x, int y, int value)
{
m_board[x][y] = value; //Visual Studio breaks the program here.
}
I allocate the double pointer properly.
And I set the board at the outside of this classes.
void Block::SetBoard(Board* board)
{
m_board = board;
}
And this is my block class.
class Block
{
public:
Block(void);
~Block(void);
void SetObjectManager(ObjectManager* pObm);
void LoadBlock (void);
void InitBlock (void);
void UpdateBlock (void);
void ReleaseBlock (void);
void SetBoard(Board* board);
private:
ObjectManager* m_obm;
Board* m_board;
int **m_piece;
int m_xSize;
int m_ySize;
};
Consider inheriting Block in Board; This will eliminate any possible de-referencing errors or bugs, as you can access the pointer right away.
I made a program for binary heap given below-
#include<iostream>
using namespace std;
/**
* Construct the binary heap.
* capacity is the capacity of the binary heap.
*/
class BinaryHeap
{
private:
int currentSize; // Number of elements in heap
int array[]; // The heap array
void buildHeap( );
void percolateDown( int hole );
public:
bool isEmpty( ) const;
bool isFull( ) const;
int findmini( ) const;
void insert( int x );
void deleteMin( );
void deleteMin( int minItem );
void makeEmpty( );
public :
BinaryHeap( )
{
currentSize = 0;
}
BinaryHeap( int capacity )
{
array[capacity + 1];
currentSize = 0;
}
};
int main()
{
int resp, ch, choice;
int n, i;
cout << "enter the size of heap" << endl;
cin >> n;
BinaryHeap b(int n);
cout << "enter the item " << endl;
cin >> ch;
b.insert( int ch);
return 0;
}
while compiling it gives errors
request for member 'insert' in 'b', which is of non-class type 'BinaryHeap(int)'
and
expected primary-expression before 'int'
why is this happening and how could it be resolved?
Remove int from BinaryHeap b(int n); and b.insert( int ch); and you are good to go.
When you call a function you shouldn't specify the data type of the variables you call it with.
Try changing this
b.insert( int ch);
to this:
b.insert(ch);
I would like to know, how to loop through a array of int to get its value and set its value. I know how to use the for loop to to get instantly, but I am not sure how it works, when I am using in user created objects and esp using the get set method.
I am totally new to this and have very little guidance from my lectures. I hope you guys can assist to help me. This up to where I have done.
//point.h
class point {
private:
int x[4];
public:
int getx();
void setx();
};
//point.cpp
class point {
point::getx(){
// ??????
}
point::setx(){
// ???????
}
//main.cpp
int main(){
point objPoint;
objPoint.setx(/* ???? */);
???? = objPoint.getx();
}
First of all, your getx method should return int*, not just int, and your setx should receive const int* as parameter. Second, in your point.cpp file you shouldn't redeclare class point.
int* point::getx() { //version with copying
int* ans = new int[4];
for (int i = 0; i < 4; i++) {
ans[i] = x[i];
}
return ans;
}
void point::setx(const int* y) {
for (int i = 0; i < 4; i++) {
x[i] = y[i];
}
}
Then you can use them like this
int y[4] = {1, 2, 3, 4};
int* z;
objPoint.setx(y);
z = objPoint.getx();
Just don't forget to delete[] z when you're done.
If I'm understanding you correctly, you probably want something like more this:
point.h:
class Point{
private:
int x, y;
public:
int getx();
int gety();
void setx(int value);
void sety(int value);
};
point.cpp
int Point::getx() { return x; }
int Point::gety() { return y; }
void Point::setx(int value) { x = value; }
void Point::sety(int value) { x = value; }
main.cpp
int main(int argc, char *argv[])
{
Point objPoint;
objPoint.setx(1);
int x = objPoint.getx();
cout << "x=" << x << endl;
return 0
}
Even better, you might wish to define a constructor like Point (int xvalue, int yvalue).
IMHO ...