c++ finding distance between 2 points - c++

In my test program I have two points, and I want to find distance between them with my distancefrom. But I get answer 0.
Why does it give 0?
How can I fix it?
Point<2> v1;
// this should have {0.0, 0.0}
Point<2> v3 { list{2.0,3.0} };
float f = v1.distanceFrom(v3);
cout << f << endl;
I have a point.h file.
#ifndef POINT_H
#define POINT_H
#include <iostream>
#include <list>
#include <sstream>
#include <string>
using std::stringstream;
#include <cmath>
using namespace std;
template<unsigned short n>
class Point {
public:
list <float> coords = {0.0};
Point <n>() = default;
Point <n>(list<float> coords){
if (coords.size()!=n) {
throw string ("Vale koordinaatide arv");
}
this-> coords=coords;
}
string toString(){
string sone;
ostringstream ss;
sone.append("(");
auto it3= coords.begin();
while ((it3) != coords.end()){
ss << (*it3);
sone.append(ss.str());
ss.str("");
sone.append(",");
++it3;
}
sone.pop_back();
sone.append(")");
return sone;
}
float distanceFrom (Point <n> v){
float s=0;
list<float> coords;
auto it1= coords.begin();
auto it2= v.coords.begin();
while ((it1) != coords.end()){
s+=(*it1 -*it2)*(*it1-*it2);
it1++;
it2++;
}
return sqrt(s);
}
friend std::ostream& operator <<(std::ostream& out, const Point<n>& v)
{
out << "("<<"Test"<<")";
return out;
}
};
#endif

First, your coords list does not know you want its size to be n. Its size after default initialization like the following is 1:
list <float> coords = {0.0};
The proper way to construct it would be:
list <float> coords = list <float> (n, 0.0);
Second, you allocate a new coords inside the function distanceFrom:
list<float> coords;
This shadows the real coords of the point which you in fact want to use. Remove that line, and you will be fine.

#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
class pointDistance{
int x, y;
public:
pointDistance (int a, int b){
x =a;
y =b;
}
void pointShow(){
cout<<"The Point is ("<<x<<","<<y<<")"<<endl;
}
friend void Distance(pointDistance , pointDistance);
};
//formula of distance between two points:
//d =((x1^2 - x2^2) + (y1^2 - y2^2))^1/2
void Distance(pointDistance o1, pointDistance o2)
{
// pointDistance o3;
int d1,d2;
d1 = (o1.x -o2.x)*(o1.x -o2.x);
d2 = (o1.y - o2.y)*(o1.y - o2.y);
cout<<"So the distance between two point is "<< sqrt(d1+d2)<<endl;
}
int main(){
pointDistance one(4,5);
one.pointShow();
pointDistance two(0,6);
two.pointShow();
Distance(one, two);
return 0;
}

Related

How can I find a minimum value from a vector of entities?

class enemy{
....
}
std::vector<std::unique_ptr<enemy> > enemies1;
for (unsigned i = 0; i < 3; ++i)
enemies1.emplace_back(...);
for (int i = 0; i < enemies1.size(); i++) {
std::cout << i <<"x: " << enemies1[i]->rect.getPosition().x << std::endl;
}
output:
100
200
400
How could I get the minimum coordinate value from multiple enemies in the vector? I want to detect the nearest enemy from the player, eg the player's coordinate is 50 and enemies are at 100, 200, 400, as you see in the above example. I want to detect the nearest enemy in the vector.
You can use min_element from
#include <algorithm>
#include <iostream>
#include <vector>
struct enemy_t
{
explicit enemy_t(const double d) :
distance{ d }
{
}
double distance;
};
int main()
{
// create a vector of enemies using the constructor with one double
std::vector<enemy_t> enemies{ 100.0,400.0,200.0,10.0 };
// the last argument to min_element is a lambda function
// it helps you define by what condition you want to find your element.
auto enemy = std::min_element(enemies.begin(), enemies.end(), [](const enemy_t& lhs, const enemy_t& rhs)
{
return lhs.distance < rhs.distance;
});
std::cout << "The minimum distance found = " << enemy->distance << "\n";
return 0;
}
For finding out the minimum you can use :
auto result = std::min_element(enemies.begin(), enemies.end(), [](auto a, auto b){return a->rect.getPosition()< b->rect.getPosition();});
std::cout<<"minimum is: "<<(**result).rect.getPosition()<<std::endl;
The above example will print out the position of the closest(minimum) enemy as you want. You just need to add the above two statements into your program.
To confirm that this works(compile and gives the expected result), below i have given an example whose output can be seen here.
#include <vector>
#include <iostream>
#include <algorithm>
struct Rectangle
{
int getPosition() const
{
return position;
}
Rectangle(int p):position(p)
{
}
int position = 0;
};
struct enemy
{
Rectangle rect;
enemy(int p): rect{p}
{
}
};
int main()
{
std::vector<enemy*> enemies;
enemy e1(600),e2(200),e3(400),e4(300), e5(100);
enemies.push_back(&e1);
enemies.push_back(&e2);
enemies.push_back(&e3);
enemies.push_back(&e4);
enemies.push_back(&e5);
auto result = std::min_element(enemies.begin(), enemies.end(), [](auto a, auto b){return a->rect.getPosition()< b->rect.getPosition();});
std::cout<<"minimum is: "<<(**result).rect.getPosition()<<std::endl;
return 0;
}

Understanding Vector classes and Tournament selection

I want to be able to compare the "overall" values of a person with another person. I'm unsure if I'm storing them correctly and I don't know how to compare them correctly. I don't know how to access the "overall" values of any single person, which is what I think is bugging me the most.
Header file
#ifndef Population_h
#define Population_h
class population
{
friend class person;
private:
int size;
int generation;
public:
void setsize(int x);
void tournament_selection(population x, int z);
};
class person
{
friend class population;
private:
float fit1;
float fit2;
float overall;
public:
void generatefit();
void setfit();
void langerman();
void printinfo();
};
#endif
Population.cpp
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <random>
#include <string>
#include <CMATH>
#include <vector>
#include "Population.h"
using namespace std;
void person ::generatefit()
{
float randomnumb1;
float randomnumb2;
//float((rand() % 10)*0.1);
randomnumb1 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
randomnumb2 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
fit1 = randomnumb1;
fit2 = randomnumb2;
}
void person::setfit()
{
float x = fit1;
float y = fit2;
}
void person::langerman()
{
overall = 3 * pow(fit1, 2) + 2 * fit2 + 0.0252;
for (overall; overall > 1; overall--);
}
void person::printinfo()
{
cout << overall << " " << endl;
}
void population::setsize(int x)
{
size = x;
}
void population::tournament_selection(population x, int total)
{
float best = 0;
for (int i = 0; i <= total; i++)
{
}
}
main.cpp
#include "Population.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <chrono>
#include <random>
#include <vector>
#include <stdlib.h>
using namespace std;
int main()
{
cout << "Program is starting " << endl;
srand(static_cast <unsigned> (time(0)));
population pop;
vector<person> popvector;
vector<person> survivor;
person *p1;
int popsize = 500;
pop.setsize(popsize);
for (int i = 0; i <= popsize; i++)
{
p1 = new person;
p1 ->generatefit();
p1->setfit();
p1->langerman();
popvector.push_back(*p1);
delete p1;
}
cout << "The fit values of the person are listed here: " << endl;
vector<person> ::iterator it; //iterator to print everything in the vector
for (it = popvector.begin(); it != popvector.end(); ++it)
{
it->printinfo();
}
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); // generate a seed for the shuffle process of the vector.
cout << "Beggining selection process" << endl;
shuffle(popvector.begin(), popvector.end(), std::default_random_engine(seed));
//want to pick consecutive parents
int j = 0;
}
I want to be able to compare people, store the "winners" into the "survivors" vector and then proceed to use the "survivor" vector to create a new population with the use of crossover and mutation for X generations.
You could use operator overloading to set a customized "Rule" of comparing the fitness level of two human beings. std::string is a perfect example": equal operations can be carried out directly by if(str1 == str2) instead of if(!strcmp(str1, str2)), demonstrating the virtue of operator overloading technique.
The following code should suit your needs:
class person {
friend class population;
private:
float fit1;
float fit2;
float overall;
public:
void generatefit();
void setfit();
void langerman();
void printinfo();
//Overloading '<' operator
bool operator(const person&);
};
//The following function defines
//rule of fitness in the jungle
bool person::operator < (const person& p2){
//This is just an example, you can define your own rules
return overall < p2.overall;
}
Once the comparing rule has been established, you can sort your population by that very rule:
//The "less fit" rule is defined so the population will be sorted
//in ascending order, if you want to sort them by descending order,
//just change the definition of your fitness rules accordingly.
sort(popvector, popvector + popsize);
Or you can use an ordered container to store population in the first place. Such choice can be set, map or priority_queue. The elements in ordered container will always follow the exact order you designated when you declared such container objects.
In your case I would suggest priority_queue because you can easily pop out the most unfitful human being from the top of the pile, like this:
#include<priority_queue>
//Still, the definition of "priority" is required beforehand
priority_queue<person> pqPerson;
person tmp;
for(int i = 0; i < popsize; ++i){
tmp.setfit(fit1, fit2, overall);
pqPerson.push(tmp);
}
for(int generation = 0; generation < X; +=generation){
//The weakest group will perish
for(int j = 0; j < tollSize; ++j){
pqPerson.pop();
}
//Crossover and Mutation process
}

Overloading i/o operators in C++ for polynomials

I got this project where I have to overload the i/o operators to read and write polynomials. Unfortunately I can't seem to get it to work.
I have the header file:
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <iostream>
using namespace std;
class Polynomial
{
public:
Polynomial();
Polynomial(int degree, double coef[]);
int degree;
double coef[ ];
friend istream& operator>>(istream&,Polynomial& );
friend ostream& operator<<(ostream&,const Polynomial&);
virtual ~Polynomial();
};
#endif // POLYNOMIAL_H
and the cpp file:
#include "Polynomial.h"
#include<iostream>
#include<string>
using namespace std;
Polynomial::Polynomial()
{
//ctor
}
Polynomial::~Polynomial()
{
//dtor
}
Polynomial::Polynomial(int d, double c[])
{
degree = d;
double coef [degree+1];
for(int i = 0; i < d+1; i++)
{
coef[i] = c[i];
}
}
istream& operator>>(istream& x, const Polynomial& p)
{
cout<<"The degree: ";
x>>p.degree;
for(int i = 0; i < p.degree+1; i++)
{
cout<<"The coefficient of X^"<<i<<"=";
x>>p.coef[i];
}
return x;
}
ostream& operator<<(ostream& out, const Polynomial& p)
{
out << p.coef[0];
for (int i = 1; i < p.degree; i++)
{
out << p.coef[i];
out << "*X^";
out << i;
}
return out;
}
In the name I am trying to read a polynomial and then to write another one:
#include <iostream>
using namespace std;
#include "Polynomial.h"
int main()
{
Polynomial p1();
cin >> p1;
int degree = 2;
double coef [3];
coef[0]=1;
coef[1]=2;
coef[3]=3;
Polynomial p(degree, coef);
cout<<p;
return 0;
}
When I run the program it just freezes and I can't seem to find the error.
Any ideas?
Polynomial::Polynomial(int d, double c[])
{
degree = d;
double coef [degree+1];
for(int i = 0; i < d+1; i++)
{
coef[i] = c[i];
}
}
Here, you create local array coef (with non-standard C++ btw) and then assign to it. Your member coeff is not initialized to anything meanigfull (and makes little sense the way it is right now in the first place).
Instead of double coef[] you should use std::vector like this:
struct polynomial {
std::vector<double> coef;
// No need for member varaible degree, vector knows its lengths
polynomial (const std::vector<double> &coeffs) : coef (coeffs) {}
};
And then define all other constructors you need to do something meaningful. Alternatively, you can leave out constructors entirely and directly assign the coefficient vector. Then you can for example functions like
int degree (const polynomial &p) {
return p.coef.size() - 1;
}
or
std::ostream &operator << (std::ostream &out, const polynomial p) {
if (p.coef.size() == 0) {
out << "0\n";
return out;
}
out << p.coeff[0];
for (int i = 1; i < p.coef.size(); ++i)
out << " + " << p.coef[i] << "*X^i";
out << "\n";
return out;
}
(1)
double coef[];
This is non-standard approach to have un-sized/dynamic-sized array on stack. You better give the array some size, OR make it a pointer and allocate memory yourself; OR use vector<double>
(2)
You are creating a local variable in constructor, which will hide the member-variable in class. If you are using pointer approach, you need to allocate it properly here in constructor. With either approach, you should initialize the (member) variable coef with zeros, ideally.
(3)
Polynomial p1();
This effectively declares a function named p1 which would return a Polynomial and not a variable of tyoe Polynomial. You may want to use:
Polynomial p1;

Implementing elements of a vector of type class

I'm using a class 'triangle' which is expressed as a vector of type 'vertex', 'vertex' being a structure consisting of an x and y value. I have a member function in 'triangle' that is supposed to return the area using heron's formula. Everything works fine until I try to output the area in the main function. Here is my code
vertex.h file
#ifndef VERTEX_H
#define VERTEX_H
#include <iostream>
struct vertex
{
double x, y;
vertex(double ix = 0.0, double iy = 0.0)
{
x = ix;
y = iy;
}
};
#endif // VERTEX_H
triangle.h file
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include <iostream>
#include <vector>
#include "vertex.h"
class triangle
{
public:
triangle(vertex iv0 = vertex(), vertex iv1 = vertex(), vertex iv2 = vertex());
// pre:
// post: empty triangle
triangle(const triangle & source);
// pre:
// post: triangle created and initialized to given triangle source
vertex operator[](size_t i) const;
// pre: 0 <= i < 3
// post: return vertex i in this triangle
double area() const;
//pre:
//post: returns area of triangle
private:
std::vector<vertex> v;
};
std::ostream & operator << (std::ostream & os, const triangle & p);
std::istream & operator >> (std::istream & is, triangle & p);
#endif // TRIANGLE.H
triangle.cpp file
#include <cassert>
#include <vector>
#include <math.h>
#include "triangle.h"
triangle::triangle(vertex iv0, vertex iv1, vertex iv2) : v(3)
{
v[0] = iv0;
v[1] = iv1;
v[2] = iv2;
}
triangle::triangle(const triangle &p)
{
v = p.v;
}
vertex triangle::operator[] (std::size_t i) const
{
assert(i < v.size());
return v[i];
}
double triangle::area() const
{
double a, b, c;
double s;
a = sqrt(pow((v[0].x-v[1].x), 2)+pow((v[0].y-v[1].y), 2));
b = sqrt(pow((v[1].x-v[2].x), 2)+pow((v[1].y-v[2].y), 2));
c = sqrt(pow((v[2].x-v[0].x), 2)+pow((v[2].y-v[0].y), 2));
s = (a+b+c)/2;
return sqrt(s*(s-a)*(s-b)*(s-c));
}
//PROBLEM IS HERE^
//(used distance formula to find side lengths a, b, and c)
main function
#include <iostream>
#include "triangle.h"
using namespace std;
int main()
{
triangle t;
t[0] = vertex(2,3);
t[1] = vertex(5,4);
t[2] = vertex(3,7);
cout << t << endl;
cout << t.area() << endl;
cout << t.operator [](2) << endl;
return 0;
}
Since you are initialising your triangle using operator[], you need to make a non-const version of that function that returns a reference. Generally you return a const reference from the const version too, rather than by value:
const vertex& triangle::operator[] (std::size_t i) const
{
assert(i < v.size());
return v[i];
}
vertex& triangle::operator[] (std::size_t i)
{
assert(i < v.size());
return v[i];
}
Your compiler really shouldn't have let you get away with the code you posted. Modifying an rvalue should be an error, or at the very least a warning. Make sure you compile with warnings turned on, and read them!
The issue has to do with how you are initializing the triangle object. Try initializing it this way:
int main()
{
triangle t (vertex(2,3), vertex(5,4), vertex(3,7));
cout << t.area() << endl;
return 0;
}
Another less ideal solution would be to make "v" a public member and then assign the values this way:
triangle t;
t.v[0] = vertex(2,3);
t.v[1] = vertex(5,4);
t.v[2] = vertex(3,7);

VS 2008 C++ object array

So I have a class Coord which is a screen location (x, y) and a class Grid which should be an array of 13 of these Coords, read in from a text file.
The error I'm bumping against is error C2512: 'Coord' : no appropriate default constructor available grid.h 26
Although I have two constructors for the Coord.h, I thought it would use the input stream one? Kinda hacking bits and pieces from other sources here and learning at the same time so please excuse me if I'm overlooking something obvious.
Coord.h
# pragma once
// class for whole screen positions
#include "DarkGDK.h"
#include <istream>
using std::istream;
class Coord
{
float cx, cy;
public:
Coord(float x, float y) : cx(x), cy(y) {} //set components directly
Coord(istream& input); //set from input
float x()
{
return cx;
}
float y()
{
return cy;
}
Coord operator+(const Coord& c);
};
Coord::Coord(istream& input)
{
input >> cx >> cy;
}
Coord Coord::operator+(const Coord& c)
{
return Coord(cx+c.cx, cy+c.cy);
}
Grid.h
# pragma once
// class for the grid array
#include "DarkGDK.h"
#include "Coord.h"
#include <fstream>
#include <iostream>
using namespace std;
const int N = 13;
const char filename[] = "grid.txt";
class Grid
{
Coord gridpos[N];
public:
Grid();
void FillGrid(); //read-in coord values
};
Grid::Grid()
{
FillGrid();
}
void Grid::FillGrid()
{
int i;
ifstream filein(filename, ios::in); //file for reading
for(i=0; !filein.eof(); i++)
{
filein >> gridpos[i].x >> gridpos[i].y; //read in
filein.close();
}
}
Any help is appreciated, thanks.
There are numerous little errors in your code. Here's a version that works with some annotations.
#include <fstream>
#include <iostream>
using namespace std;
const int N = 13;
const char filename[] = "grid.txt";
class Coord
{
float cx, cy;
public:
// Default constructor required to declare array: eg Coord c[23];
Coord() : cx(0), cy(0)
{}
Coord(float x, float y) : cx(x), cy(y)
{}
// You were returning float instead of float& which means you could not update
float& x()
{
return cx;
}
float& y()
{
return cy;
}
Coord Coord::operator+(const Coord& c)
{
return Coord(cx+c.cx, cy+c.cy);
}
friend istream& operator>>(istream& input, Coord& rhs)
{
input >> rhs.cx >> rhs.cy;
return input;
}
};
class Grid
{
Coord gridpos[N];
public:
Grid()
{
FillGrid();
}
void FillGrid()
{
int i;
ifstream filein(filename, ios::in); //file for reading
for(i=0; !filein.eof(); i++)
{
filein >> gridpos[i];
}
// Close the file after you have finished reading from it
filein.close();
}
};
int main()
{
Grid g;
return 0;
}