The essence of what I want to do is to take two instances of Vector2D and create a third vector that is to be returned and made into the third instance. The problem I am facing is that I am not entirely sure on how to go ahead in doing so. I have tried to find the syntax for sending in instances, if there is such a one, but I have not managed to find anything useful in any of my books.
#include<iostream>
#include<string>
#include<array>
using namespace std;
class vector2D
{
public:
array<float, 2> get()
{
return xy_coord;
}
void set(float x, float y)
{
xy_coord[0] = x;
xy_coord[1] = y;
}
array<float, 2> vectorAdd(a, b)
{
array<float, 2> c;
for (int i = 0; i < 2; i++)
{
c[i] = a[i] + b[i];
}
return c;
}
private:
array<float, 2> xy_coord;
};
int main()
{
string y;
vector2D a, b, c;
array<float, 2> temp;
a.set(2.0, 3.0);
b.set(4.0, 5.0);
temp = c.vectorAdd(a, b);
c.set(temp[0], temp[1]);
getline(cin, y);
}
The idea is to send in the instances a and b to vectorAdd and sum them up and then set c equal to the returned value (I am sure there is a better way to write the code in the main(), but I am not sure how). In short, what would a and b need to be defined as to make this work, assuming it can work at all.
Maybe you could do something like this instead, so you don't have to pass array around:
#include <iostream>
class Vector2D
{
private:
double _x;
double _y;
public:
Vector2D() = delete;
Vector2D(double x, double y) : _x(x), _y(y) {}
double X() const { return _x; }
double Y() const { return _y; }
Vector2D operator+(Vector2D const &v) const
{
return Vector2D(X() + v.X(), Y() + v.Y());
}
};
int main()
{
Vector2D v1(10.0, 20.0);
Vector2D v2(100.0, 200.0);
Vector2D v3 = v1 + v2;
std::cout << v3.X() << " " << v3.Y();
return 0;
}
Prints:
110 220
Do you need to use array<float, 2>? Have you thought of using pair<float, float>?
A lot (all?) of the operations that you have in your Vector2D class come for free with Pair<>.
Then you just create operator+ as others have suggested.
#include <iostream>
#include <utility>
using namespace std;
using Coord = pair<float, float>;
template <typename L, typename R>
Coord operator+(const L& x, const R& y) { return std::make_pair(x.first + y.first, x.second + y.second); }
int main()
{
Coord a { 5.0f, 6.0f };
Coord b { 7.0f, 9.0f };
Coord c = a + b;
std::cout.precision(5);
std::cout << "c= (" << std::fixed << c.first << ", " << c.second << ")" << std::endl;
return 0;
}
Related
I need implement the class Option_Pricer that encapsulates all the functions relevant to price both call and put options. The teacher is giving me a code listing (.cpp file) that I have to turn into a class. All the functions that I used in my class are therefore coming from the teacher. I simply have to implement them as a class.
Here is what I have done so far: I have split the code into two different files. One is called option_pricer.hpp and is used as an header for the main file option_pricer.cpp.
//option_pricer.hpp
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
class Option_Pricer {
private:
void init();
public:
double S;
double K;
double r;
double v;
double T;
double x;
double j;
public:
//Constructors
call_price();
put_price();
norm_pdf();
norm_cdf();
d_j() const;
// Assignment operator
call_price& operator = (const call_price& call);
put_price& operator = (const put_price& put);
};
Here is the main file:
//option_pricer.cpp
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#include "option_pricer.hpp"
double Option_Pricer::norm_pdf(const double& x) const {
return (1.0/(pow(2*M_PI,0.5)))*exp(-0.5*x*x);
}
double Option_Pricer::norm_cdf(const double& x) const {
double k = 1.0/(1.0 + 0.2316419*x);
double k_sum = k*(0.319381530 + k*(-0.356563782 + k*(1.781477937 + k*(-1.821255978 + 1.330274429*k))));
if (x >= 0.0) {
return (1.0 -(1.0/(pow(2*M_PI,0.5)))*exp(-0.5*x*x) * k_sum);
}
else {
return 1.0 - norm_cdf(-x);
}
}
double Option_Pricer::d_j(const int& j, const double& S, const double& K, const double& r, const double& v, const double& T) const {
return (log(S/K) + (r + (pow(-1,j 1))*0.5*v*v)*T)/(v*(pow(T,0.5)));
}
double Option_Pricer::call_price(const double& S, const double& K, const double& r, const double& v, const double& T) const {
return S * norm_cdf(d_j(1, S, K, r, v, T))-K*exp(-r*T) * norm_cdf(d_j(2, S, K, r, v, T));
}
double Option_Pricer::put_price(const double& S, const double& K, const double& r, const double& v, const double& T) const {
return -S*norm_cdf(-d_j(1, S, K, r, v, T))+K*exp(-r*T) * norm_cdf(-d_j(2, S, K, r, v, T));
}
int main() {
Option_Pricer p;
p.S = 100.0;
p.K = 100.0;
p.r = 0.05;
p.v = 0.2;
p.T = 1.0;
double call_price = p.call_price();
double call_put = p.put_price();
// Finally we output the parameters and prices
std::cout << "Underlying: " << p.S << std::endl;
std::cout << "Strike: " << p.K << std::endl;
std::cout << "Risk-Free Rate: " << p.r << std::endl;
std::cout << "Volatility: "<< p.v << std::endl;
std::cout << "Maturity: " << p.T << std::endl;
std::cout << "Call price: " << call_price << std::endl;
std::cout << "Put price: " << call_put << std::endl;
return 0;
}
However, as you can guess, my code isn't compiling really well. My most common error is the following:
option_pricer.cpp:7:8: error: no declaration matches ‘double Option_Pricer::norm_pdf(const double&) const’
7 | double Option_Pricer::norm_pdf(const double& x) const {
| ^~~~~~~~~~~~~
I don't understand how I should call the norm_pdf from outside of the header (same question for norm_cdf and d_j).
I'm fairly new to C++ (was using Python before) and therefore don't understand yet how am I supposed to access the variables (S, K,...) from outside of my class.
Help will be appreciated! Thank you!
You need to make and understand the distinction between a class and an object. Very simply, an object is a collection of values in memory, and a class is a description of those values and of code that will use data organized according to the class description.
So, since Option_Pricer is a class, it doesn't make sense to say Option_Pricer.S = 100.0; in your main() method. You need to create an object of type Option_Pricer, and then fill that object's memory region with the values you want. A common method for doing that - especially in your case where you are simply initializing the object with numeric data - is to create and use a constructor, although you could modify your init() method to take arguments and set values and that would be fine too. You can even set the values one-by-one as you have done, since you made the values public, but you have to modify the object, not the class.
Ex.
int main()
{
Option_Pricer p(100.0, 100.0, 0.5, 0.2, 1.0);
double call_price = p.call_price();
// or
Option_Pricer p2;
p2.init(100.0, 100.0, 0.5, 0.2, 1.0);
double call_price2 = p2.call_price();
// or, if you like typing or want the meaning of the numbers to be super clear
Option_Pricer p3;
p3.S = 100.0;
p3.K = 100.0;
p3.r = 0.05;
p3.v = 0.2;
p3.T = 1.0;
// ...
This doesn't address everything that's wrong with your code, but I'd start by addressing the above. I think the problems that others are pointing out will be easier to sort out once you get the concept of an object squared away.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Ok Guys My Question here is simple.. I want to construct a getter and setter for diffrent value type.. Basically function overloading but with getters and setters.. i tried it like this
#include <iostream>;
class Vectors {
public:
Vectors() {};
Vectors(int a, int b) {
x = a, y = b;
}
int getX() {
return x;
}
int getY() {
return y;
}
float getX() {
return (float)x;
}
float getY() {
return (float) y;
}
friend Vectors operator+(const Vectors& v1, const Vectors& v2);
friend Vectors operator/(const Vectors& v1, const Vectors& v2);
protected:
int x, y;
private:
};
Vectors operator+(const Vectors& v1, const Vectors& v2) {
Vectors brandNew;
brandNew.x = v1.x + v2.x;
brandNew.y = v1.y + v2.y;
return (brandNew);
};
Vectors operator/(const Vectors& v1, const Vectors& v2) {
Vectors brandNew(v1.x / v2.x, v1.y/v2.y);
return brandNew;
}
int main() {
Vectors v1(2, 3);
Vectors v2(4, 5);
Vectors v3;
v3 = v1 + v2;
Vectors v4 = v1 / v2;
std::cout << "VECTOR 4 X : " << v4.getX() << std::endl;
std::cout << "VECTOR 4 Y : " << v4.getY() << std::endl;
std::cout << "Vector V3 X : " << v3.getX() << std::endl;
std::cout << "VECTOR V3 Y : " << v3.getX() << std::endl;
}
But Obviously it said cant do function overloading and the only type diffrent is return type..
Of course you're not using enough templates. Templates solve problems in C++. Use them. Love templates.
struct YeeTemplates {
float F;
template <typename T>
T getF() { return F; }
} y;
float f = y.getF<float>();
int i = y.getF<int>();
There's no way to overload a function without changing the arguments that I'm aware of. You need to either change the function name (call it getXFloat() or something) or just to the cast after calling the function like:
float the_x_value = static_cast<float>(vec.getX());
I would go for the second option.
You can't overload methods based on return type.
You can overload functions on it's input paramaters.
For example:
void fun1(int a,char b);
void fun1(float a,char b);
void fun1(float a,int a,char b);
http://www.tutorialspoint.com/cplusplus/cpp_overloading.htm
Another option you have is to not return the result as the return value. Instead:
...
void getX( float& result) const {
result = static_cast<float>(x);
}
void getX( int& result) const {
result = x;
}
...
Just adding to the list of options, not saying this is the best solution.
Is there a way to bind member function to something like member variable?
Let's say i have simple vector struct:
struct Vec3 {
int x, y, z;
Vec2 xy() const { return Vec2(x, y); }
Vec2 xz() const { return Vec2(x, z); }
Vec2 yz() const { return Vec2(y, z); }
}
Now i can use it like:
Vec3 t = { 5, 3, 2 };
Vec2 s = t.xy() + t.yz();
But is there a way i could use it like:
Vec3 t = { 5, 3, 2 };
Vec2 s = t.xy; // this here ? execute function without '()'.
While C++ does not offer properties by default, you can implement them pretty easily by yourself.
Here is a simplistic approach:
#include <functional>
template<typename T>
struct property
{
public:
typedef std::function<T()> getter;
typedef std::function<void(T)> setter;
public:
property(getter get, setter set)
: get_(get)
, set_(set)
{ }
operator T() const { return get_(); }
property& operator=(T x) { set_(x); return *this; }
private:
getter get_;
setter set_;
};
We can now rewrite your Vec3 class using these 'properties':
class Vec3
{
public:
Vec3(int vx, int vy, int vz)
: x(std::bind(&Vec3::get_x, this), std::bind(&Vec3::set_x, this, std::placeholders::_1))
, y(std::bind(&Vec3::get_y, this), std::bind(&Vec3::set_y, this, std::placeholders::_1))
, z(std::bind(&Vec3::get_z, this), std::bind(&Vec3::set_z, this, std::placeholders::_1))
, xy(std::bind(&Vec3::get_xy, this), std::bind(&Vec3::set_xy, this, std::placeholders::_1))
, xz(std::bind(&Vec3::get_xz, this), std::bind(&Vec3::set_xz, this, std::placeholders::_1))
, yz(std::bind(&Vec3::get_yz, this), std::bind(&Vec3::set_yz, this, std::placeholders::_1))
, x_(vx)
, y_(vy)
, z_(vz)
{ }
property<int> x;
property<int> y;
property<int> z;
property<Vec2> xy;
property<Vec2> xz;
property<Vec2> yz;
protected:
int get_x() { return x_; }
void set_x(int x) { x_ = x; }
int get_y() { return y_; }
void set_y(int y) { y_ = y; }
int get_z() { return z_; }
void set_z(int z) { z_ = z; }
Vec2 get_xy() { return { x_, y_ }; }
void set_xy(Vec2 xy) { x_ = xy.x; y_ = xy.y; }
Vec2 get_xz() { return { x_, z_ }; }
void set_xz(Vec2 xz) { x_ = xz.x; z_ = xz.y; }
Vec2 get_yz() { return { y_, z_ }; }
void set_yz(Vec2 yz) { y_ = yz.x; z_ = yz.y; }
private:
int x_, y_, z_;
};
Which can be used like this:
std::ostream& operator<<(std::ostream& out, const Vec2& v2)
{
out << '[' << v2.x << ", " << v2.y << ']';
return out;
}
std::ostream& operator<<(std::ostream& out, const Vec3& v3)
{
out << '[' << v3.x << ", " << v3.y << ", " << v3.z << ']';
return out;
}
int main(int argc, char** argv)
{
Vec3 v3 { 2, 0, 1 };
std::cout << v3 << std::endl;
v3.y = 3;
std::cout << v3.xy << std::endl;
std::cout << v3.xz << std::endl;
std::cout << v3.yz << std::endl;
return 0;
}
As you can see, what you are asking is possible, it just requires a lot of code.
See the live example on ideone
You can do it by adding helper structs with user-defined convertion functions to Vec2, each containing a reference to the parent (Vec3) in order to have access to its members.
A working example (Visual Studio 2015 update 3):
#include <iostream>
struct Vec2 {
int x, y;
};
struct Vec3 {
int x, y, z;
struct XY {
Vec3& outer;
XY(Vec3& _outer) : outer {_outer} {};
operator Vec2() { return Vec2 {outer.x, outer.y}; };
} xy;
struct XZ {
Vec3& outer;
XZ(Vec3& _outer) : outer {_outer} {};
operator Vec2() { return Vec2 {outer.x, outer.z}; };
} xz;
struct YZ {
Vec3& outer;
YZ(Vec3& _outer) : outer {_outer} {};
operator Vec2() { return Vec2 {outer.y, outer.z}; };
} yz;
Vec3(int _x, int _y, int _z) :
xy {*this}, xz {*this}, yz {*this},
x {_x}, y {_y}, z {_z} {};
};
int main() {
Vec3 t {5,3,2};
Vec2 xy = t.xy; // look, mom, no parentheses!
Vec2 xz = t.xz;
Vec2 yz = t.yz;
std::cout << xy.x << ", " << xy.y << std::endl;
std::cout << xz.x << ", " << xz.y << std::endl;
std::cout << yz.x << ", " << yz.y << std::endl;
}
Output:
5, 3
5, 2
3, 2
So I am working on "TEMPLATES" and I'm required to make a 3 attempt of a function called PrintMax -it's obvious what it does-, to print the maximum element in an array of 3 elements, each attempt is for a different data type in this array -double/int/complex-. So I'm required to first, create the class Complex, and its required operator overloads, after that I use the PrintMax function as template function to work on the 3 types of arrays.
The problem here lies within the 3rd array of course, I can't write the elements of Complex into the array in this for ( a + bi ), because this is my class Complex :
class Complex
{
private :
int imaginary;
int real;
public:
Complex (int = 0, int = 0);
~Complex ();
int getImaginary();
int getReal();
void setImagniary(int i);
void setReal (int r);
bool operator > (Complex&);
};
You can notice, I overloaded operator > to check, but I also have a little problem besides not being able to write the elements in that way, the second problem is I can't -or sleepy and my brain is dying- calculate which is maximum in this array of Complex numbers :
// Input: Complex Array
// 1+3i, 2+4i, 3+3i
// Expected Output: 2+4i
So I want to assign them in the array with this form : Arr[3] = {1+3i, 2+4i, 3+3i};
Why is that the expected output, why not 3+3i ?
Thanks for reading ~
It seems to me that you are looking for something like:
template <typename T> void PrintMax(T array[])
{
// It is assumed that array has 3 elements in it.
std::cout <<
array[0] > array[1] ?
(array[0] > array[2] ? array[0] : array[2]) :
(array[1] > array[2] ? array[1] : array[2])
std::endl;
}
You could use something like the following. Note that there are no range checks in the code, it is just to demonstrate a way how you could solve your problem.
Plus i would suggest you to use a container (eg. std::vector) instead of plain arrays.
#include <algorithm>
#include <cmath>
#include <iostream>
class Complex {
private:
int imaginary;
int real;
public:
Complex(int r, int i) :
imaginary(i), real(r) {
}
~Complex() {
}
int getImaginary() const {
return imaginary;
}
int getReal() const {
return real;
}
void setImaginary(int i) {
imaginary = i;
}
void setReal(int r) {
real = r;
}
double getAbsolut() const {
return std::abs(std::sqrt(std::pow(imaginary, 2) + std::pow(real, 2)));
}
friend bool operator<(const Complex& lhs, const Complex& rhs);
friend std::ostream& operator<<(std::ostream& stream,
const Complex& complex);
};
bool operator<(const Complex& lhs, const Complex& rhs) {
return lhs.getAbsolut() < rhs.getAbsolut();
}
std::ostream& operator<<(std::ostream& stream, const Complex& complex) {
stream << "Complex(" << complex.real << "+" << complex.imaginary
<< "i)";
return stream;
}
template<int size, class T>
void getMax(const T arr[]) {
T max_value = arr[0];
for (size_t i = 1; i < size; ++i) {
max_value = std::max(max_value, arr[i]);
}
std::cout << "max: " << max_value << std::endl;
}
int main(int argc, char **argv) {
Complex arr_complex[] = { Complex(3, 3), Complex(2, 4), Complex(1, 3) };
int arr_int[] = { 3, 5, 1 };
double arr_double[] = { 2.3, 5.6, 9.1 };
getMax<3>(arr_complex);
getMax<3>(arr_int);
getMax<3>(arr_double);
return 0;
}
I have a set of points (x,y,z). I want to sort these data using first column and 2nd and 3rd columns should be rearranged according to the sorting 1st column. is it possible to do this in c++, if so could you pls help me.
Herewith I am attaching codes of my implementation but I got a error message “invalid conversion from ‘const’ vod*’ to ‘const int [*][3]’ “ in line 31 and 32. I tried this using several methods but my effort was not success yet. I used here ‘qsort’ for this, are there any other methods or can I use ‘sort’ in to do this. Since I have a very big data set I wish to use a fast method.
So what I need at the end the data set which is sorted using only 1st column like following example:
before sort
34 12 12
12 34 15
24 20 34
13 11 10
40 23 32
after sort
12 34 15
13 11 10
24 20 34
34 12 12
40 23 32
if any good methods help me to write codes …thanks
#include <iostream>
#include <cstdlib>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Point
{
private:
double x;
double y;
double z;
public:
Point(){};
~Point(){};
Point(double X, double Y, double Z){
x=X;y=Y;z=Z; }
double X(){return x;}
double Y(){return y;}
double Z(){return z;}
};
int cmp ( const void *pa, const void *pb ) {
const int (*a)[3] = pa;
const int (*b)[3] = pb;
if ( (*a)[1] < (*b)[1] ) return -1;
if ( (*a)[1] > (*b)[1] ) return +1;
return 0;
}
int main ( ) {
vector<Point> points;
int input_x,input_y,input_z;
int i=0;
while(i<6){//data set,it is a example, actual data come from a file
cout<<"x: ";cin>>input_x;
cout<<"y: ";cin>>input_y;
cout<<"z: ";cin>>input_z;
Point point(input_x,input_y,input_z);
points.push_back(point);
i++;
}
for (int i=0;i<points.size();i++){//before sort
cout<<points[i].X()<<" "<<points[i].Y()<<" "<<points[i].Z()<<endl;
}
qsort( points, 6, sizeof points[0], cmp );
for (int i=0;i<points.size();i++){//after sort
cout<<points[i].X()<<" "<<points[i].Y()<<" "<<points[i].Z()<<endl;
}
system("PAUSE");
return 0;
}
It's almost certainly easiest to use std::sort instead of qsort:
class Point {
int x, y, z;
public:
Point(int x, int y, int z) : x(x), y(y), z(z) {}
bool operator<(Point const &other) {
return x < other.x;
}
// skipping the reading and other stuff for now...
};
int main() {
std::vector<Point> points;
// add some Points to `points` here.
// sort using order defined in Point::operator<:
std::sort(points.begin(), points.end());
return 0;
}
Edit: to keep the comparison separate from the items being compared, you use a separate function or functor to do the comparison, and pass that to std::sort. There are a few things about your class that you really want to change in any case though -- at the very least, since your Point::X(), Point::Y() and Point::Z() don't modify the Point object, you want to make them const member functions. Once you've done that, the sorting is fairly trivial:
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
class Point {
double x, y, z;
public:
double X() const { return x; }
double Y() const { return y; }
double Z() const { return z; }
Point(double x=0.0, double y=0.0, double z=0.0) : x(x), y(y), z(z) {}
};
namespace std {
ostream &operator<<(ostream &os, Point const &p) {
return os << "(" << p.X() << ", " << p.Y() << ", " << p.Z() << ")";
}
}
struct byX {
bool operator()(Point const &a, Point const &b) {
return a.X() < b.X();
}
};
int main(){
std::vector<Point> points;
for (int i=0; i<10; i++)
points.push_back(Point(rand(), i, i));
std::cout << "Unsorted:\n";
std::copy(points.begin(), points.end(),
std::ostream_iterator<Point>(std::cout, "\n"));
std::sort(points.begin(), points.end(), byX());
std::cout << "\nSorted:\n";
std::copy(points.begin(), points.end(),
std::ostream_iterator<Point>(std::cout, "\n"));
return 0;
}
Technically, I suppose I should add one more minor detail: if the x value in any of your points is a NaN, this won't work correctly. A NaN isn't equal to anything (not even itself) which violates the strict weak ordering required for std::sort.
The arguments of the cmp function are actually const Point *px in your case. You may not be able to declare them as arguments this way, but you can surely cast the void pointers later.
Further reference here.