Storing Cartesian points in a vector and outputting distance - c++

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.

Related

How to use overload operator as condition in a if statment?

Here is the class
#include <fstream>
#include <cstdlib>
#include <math.h>
#include <iomanip>
#include <iostream>
using namespace std;
class Point {
protected:
int x, y;
double operator-(const Point &def){
return sqrt(pow((x-def.x),2.0)+
pow((y-def.y),2.0));
}
};
class Circle: public Point {
private:
int radius;
public:
Circle(){
this->x=x;
this->y=y;
this->radius=radius;
}
Circle(int x, int y, int radius){
this->x=x;
this->y=y;
this->radius=radius;
}
void printCircleInfo() {
cout << x << " " << y << " " << radius << " " ;
}
This is the operator I want to be the condition in my if statement.
bool operator==(const Circle &def){
return (x==def.x) & (y==def.y) & (radius==def.radius);
}
bool doIBumpIntoAnotherCircle(Circle anotherCircle){
if (anotherCircle.radius + radius >= *this - anotherCircle )
return true;
return false;
}
};
Here is main
int main(){
int x,y,radius;
const int SIZE = 13;
Circle myCircleArry[SIZE];
myCircleArry[0] = Circle(5,3,9);
cout << endl;
myCircleArry[0].printCircleInfo(); cout << " ; ";
ifstream Lab6DataFileHandle;
Lab6DataFileHandle.open("Lab6Data.txt");
while (!Lab6DataFileHandle.eof( )) {
for (int i = 1; i < SIZE; i++) {
Lab6DataFileHandle>>x;
Lab6DataFileHandle>>y;
Lab6DataFileHandle>>radius;
myCircleArry[i] = Circle(x,y,radius);
if (myCircleArry[0].doIBumpIntoAnotherCircle(myCircleArry[i])) {
myCircleArry[i].printCircleInfo(); cout << " ; ";
Here is the If statement
if ( operator==( Circle &def))
{cout <<"*";
}
}
}
}
Lab6DataFileHandle.close();
}
How do I use the overloaded operator as the condition of the if statement? If you need any clarification just ask other wise please leave an example in your answer.
Thank you for your time.
A == needs two arguments (even if the overload is a member), you would write the if as any other if statement:
if(circle1 == circle2) { ... }
and if there's a matching overload the compiler would transform that into something like:
if(circle1.operator ==(circle2)) { ... }

How to define a variable in a function and access and change it in another function?(c++)

I would like to know how to define a variable in one function and access and change it in another function.
For example:
#include <iostream>
void GetX()
{
double x = 400;
}
void FindY()
{
double y = x + 12;
}
void PrintXY()
{
std::cout << x;
std::cout << y;
}
int main()
{
GetX();
FindY();
PrintXY();
}
How would I access these variables from all the functions? (Obviously for this to work in real life I wouldn't need so many functions, but I think this is a nice simple example). Thanks in advance for your help!
Use function parameters to pass values to functions and return values to return results:
#include <iostream>
double GetX()
{
return 400;
}
double FindY(double x)
{
return x + 12;
}
void PrintXY(double x, double y)
{
std::cout << x;
std::cout << y;
}
int main()
{
double x = GetX();
double y = FindY(x);
PrintXY(x, y);
}
Since the question was tagged with C++, here is another option:
#include <iostream>
class Sample
{
public:
void FindY()
{
y = x + 12;
}
void PrintXY()
{
std::cout << x;
std::cout << y;
}
private:
double x = 400, y;
};
int main()
{
Sample s;
s.FindY();
s.PrintXY();
}
You want to define a variable in one function : That means you are making the variable local to that function.
You want to access and change that local variable from another function. This is not usual. Technically possible but can be done with better resource management/design.
*You can make the variable your class member and play with it.
*You can share a variable by making it global as well.
*In Tricky way :
double &GetX()
{
static double x = 400;
return x;
}
// We are accessing x here to modify y
// Then we are modifying x itself
// Pass x by reference
double &AccessAndChangeX(double& x)
{
static double y;
y = x + 12; // We are accessing x here and using to modify y.
// Let's modify x
x = 100;
return y;
}
void PrintXY(double x, double y)
{
std::cout << x;
std::cout << y;
}
int main()
{
double &x = GetX(); // Take the initial value of x. 400.
double &y = AccessAndChangeX(x);
//Print initial value of x and value of y(generated using x)
PrintXY(x, y);
// X was modified while AccessAndChangeX(x). Check if x was changed!
std::cout << "\n" << "What is the value of x now : " << GetX();
}
1st, make x, y as static, so that these exist when the function returns..
2nd, get reference, modify or do something outside the function..
#include <iostream>
double &GetX()
{
static double x = 400;
return x;
}
double &FindY( double x )
{
static double y;
y = x + 12;
return y;
}
void PrintXY(double x, double y )
{
std::cout << x;
std::cout << y;
}
int main()
{
double &x = GetX();
double &y = FindY( x );
// Now you can modify x, y, from Now On..
// .....
PrintXY( x, y );
}
By the way, I donot recommend this style of code..

class member functions for C++ newbie [duplicate]

This question already has answers here:
Visual Studio 2015 “non-standard syntax; use '&' to create a pointer to member”
(3 answers)
Closed 5 years ago.
I'm new with C++ and I'm currently studying for exams, messing around with C++ in VisualStudio and experimenting a bit. Usuall I work with Java.
I wrote a simple class to see how and if things work:
class Point
{
private:
int x;
int y;
public:
Point(int arg1, int arg2)
{
x = arg1;
y = arg2;
}
};
I tried 2 simple member functions for x and y to just double the value stored in the x and y variables.
First I tried this:
void doubleX()
{
x *= 2;
};
void doubleY()
{
y *= 2;
};
Then I tried this:
void doubleX()
{
Point::x = 2 * Point::x;
};
void doubleY()
{
Point::y = 2 * Point2::y;
};
Both are put inside the class definition.
While building through VisualStudio it alwas gives me this error warning:
"Error C3867 'Point::doubleX': non-standard syntax; use '&' to create a pointer to member"
Tried to mess around with adress pointers as well but... I don't really have a clue.
I think I know how pointers basically work, but I have no idea how to use it for my case here.
Any quick solution and explanation to this problem?
Thanks in advance!
EDIT: here's my whole code, problem is in the main now
#include "stdafx.h"
#include <iostream>
using namespace std;
class Point
{
public:
int x;
int y;
Point(int arg1, int arg2)
{
x = arg1;
y = arg2;
}
void doubleX()
{
x *= 2;
};
void doubleY()
{
y *= 2;
};
};
int main()
{
Point p(1,1);
int &x = p.x;
int &y = p.y;
cout << x << "|" << y;
p.doubleX; p.doubleY; //error message here
cout << x << "|" << y;
cin.get();
}
Maybe you didn't declare the member functions inside the class definition? Here is a full working example based on your class:
#include <iostream>
class Point
{
private:
int x;
int y;
public:
Point(int arg1, int arg2)
{
x = arg1;
y = arg2;
}
void doubleX()
{
x *= 2; /* or this->x *= 2; */
}
void doubleY()
{
y *= 2;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
Point p(2, 3);
std::cout << "p.x = " << p.getX() << " | p.y = " << p.getY() << std::endl;
p.doubleX();
p.doubleY();
std::cout << "p.x = " << p.getX() << " | p.y = " << p.getY() << std::endl;
return 0;
}
You can put this in a main.cpp file, compile and run it. I tested it with the g++ compiler and it works fine.
The answer given by Valy is correct. But I would like remind you that C++ offers you another choice of declaring and defining methods, that is declaring method inside the class declaration and defining them outside the class declaration. This enables you to easily separate interface and implementation into .h and .cpp files, respectively, as shown below:
Point.h
class Point
{
private:
int x;
int y;
public:
Point(int arg1, int arg2);
void doubleX();
void doubleY();
int getX();
int getY();
};
Point.cpp
#include "Point.h"
Point::Point(int arg1, int arg2)
{
x = arg1;
y = arg2;
}
void Point::doubleX()
{
x *= 2;
}
void Point::doubleY()
{
y *= 2;
}
int Point::getX()
{
return x;
}
int Point::getY()
{
return y;
}
// PointTest.cpp
#include "Point.h"
int main()
{
// Do something with Point here
Point pt(1, 2);
std::cout << "Original: (" << pt.getX() << ", " << pt.getY() << ")" << std::endl;
pt.doubleX();
pt.doubleY();
std::cout << "After being doubled: (" << pt.getX() << ", " << pt.getY() << ")" << std::endl;
return 0;
}
And, how to compile:
g++ -o PointTest PointTest.cpp Point.cpp
Can't comment due to reputation but it seems vc++ outputs the error message you stated if you try to call
Point::doubleX
Here's a live example of the output:
http://rextester.com/ZLCEW66682
You should create an instance of the class and call the function using parens
In your second set of functions
void doubleX()
{
Point2::x = 2 * Point2::x;
};
void doubleY()
{
Point2::y = 2 * Point2::y;
};
If you want them to be member functions of the class Point, Point::y ... this is not how you should access the member data. Only static member variables can be accessed like that. The correct way is
void doubleX()
{
this->x = 2 * this->x;
};
void doubleY()
{
this->y = 2 * this->y;
};
That is using this pointer.

Error when resizing vector of object

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.

Undefined reference to my classes? C++ Beginner

To get a bit of practice with OOP i'm trying to make a Point class (has 2 ints, x & y) and a Line class (has 2 Points).
Now when i go to build my main.cpp i get errors like..
"undefined reference to `Point::Point(float, float)' " and
" undefined reference to `Line::Line(Point, Point)'"
At a loss as to why, perhaps you could take a brief look at my files? It'd be much appreciated!
Main.cpp
#include "Point.hpp"
#include "Line.hpp"
#include <iostream>
using namespace std;
int main()
{
Point p1(2.0f, 8.0f); // should default to (0, 0) as specified
Point p2(4.0f, 10.0f); // should override default
p1.setX(17);
if ( p1.atOrigin() && p2.atOrigin() )
cout << "Both points are at origin!" << endl;
else
{
cout << "p1 = ( " << p1.getX() << " , " << p1.getY() << " )" <<endl;
cout << "p2 = ( " << p2.getX() << " , " << p2.getY() << " )" <<endl;
}
Line line(p1, p2);
Point midpoint = line.midpoint();
cout << "p1 = ( " << midpoint.getX() << " , " << midpoint.getY() << " )" <<endl;
return 0;
}
Line.hpp
#ifndef _LINE_HPP_
#define _LINE_HPP_
#include "Point.hpp"
class Line{
public:
Line(Point p1, Point p2);
//void setp1(Point p1);
//void setp2(Point p2);
//Point getp1 finish
Point midpoint();
int length();
private:
int _length;
Point _midpoint;
Point _p1, _p2;
};
#endif
Line.cpp
#include "Line.hpp"
#include <math.h>
Line::Line(Point p1, Point p2) : _p1(p1), _p2(p2)
{
}
Point Line::midpoint()
{
_midpoint.setX() = (_p1.getX()+ _p2.getX()) /2;
_midpoint.setY() = (_p1.getY()+ _p2.getY()) /2;
}
int Line::length()
{
//a^2 + b^2 = c^2
_length = sqrt( ( (pow( _p2.getX() - _p1.getX(), 2 ))
+(pow( _p2.getY() - _p1.getY(), 2 )) ) );
}
Point.hpp
#ifndef _POINT_HPP_
#define _POINT_HPP_
class Point {
public:
Point( float x = 0, float y = 0);
float getX() const;
float getY() const;
void setX(float x = 0);
void setY(float y = 0);
void setXY(float x = 0, float y = 0);
bool atOrigin() const;
private:
float _x, _y;
};
#endif
Point.cpp
#include "Point.hpp"
Point::Point(float x, float y) : _x(x), _y(y)
{
}
float Point::getX() const
{
return _x;
}
float Point::getY() const
{
return _y;
}
void Point::setX(float x)
{
//if (x >= 0 &&
_x = x;
}
void Point::setY(float y)
{
//might want to check
_y = y;
}
void Point::setXY(float x , float y )
{
setX(x);
setY(y);
}
bool Point::atOrigin() const
{
if ( _x == 0 && _y == 0)
return true;
return false;
}
In C++, not only do you have to compile main.cpp, but you also have to compile your Line.cpp and Point.cpp files. Then, when you have them all compiled into object files, you must link the object files together. This is handled automatically by some other languages such as Java.
The exact instructions on how to do this will depend on which development environment you are using.
Your Point.cpp isn't being compiled or given to the linker, try including it in your build.