I am trying to push data to my vector, but I'm met with an error:
expression must have class type
This is my code:
float calcX(float u, float v)
{
return (((-90.0*pow(u, 5) + 225.0*pow(u, 4) - 270.0*pow(u, 3) + 180.0*pow(u, 2) - 45.0*u)*cos(pi*v)));
}
float calcY(float u, float v)
{
return (160.0*pow(u, 4) - 320.0*pow(u, 3) + 160.0*pow(u, 2) - 5.0f);
}
float calcZ(float u, float v)
{
return (((-90.0*pow(u, 5) + 225.0*pow(u, 4) - 270.0*pow(u, 3) + 180.0*pow(u, 2) - 45.0*u)*sin(pi*v)));
}
typedef float point3[3];
std::vector <point3*> createEggBuffor(int n=20)
{
std::vector <point3*> egg;
for (int u = 0; u < n; u++) {
for (int v = 0; v < n; v++) {
egg[u][v][0].push_back(calcX(static_cast<float>(u) / (n - 1), static_cast<float>(v) / (n - 1)));
egg[u][v][1].push_back(calcY(static_cast<float>(u) / (n - 1), static_cast<float>(v) / (n - 1)));
egg[u][v][2].push_back(calcZ(static_cast<float>(u) / (n - 1), static_cast<float>(v) / (n - 1)));
}
}
return egg;
}
What this error means?
egg[u] is a point3*. egg[u][v] is a point3 (which is an array of 3 floats). So egg[u][v][N] is a float. float is a built-in type, and does not have a member function named push_back, or any members at all. The error is telling you that, since it is not a class type, you can't use the dot operator to access members of it (since it doesn't have any).
If you're trying to push back elements onto your egg vector, it would look like this:
egg.push_back(something);
Where something is an expression of type point3*.
Related
My code is supposed to calculate the 100th element of the sequence $x_0=1 ; x_i=\dfrac{x_{i-1}+1}{x_{i-1}+2}, i=1,2, \ldots$
I wrote iterative and recursive functions, but the results are not equal. Is it due to the lost of decimals?
Here is my driver code. The data from the file is i=100.
int main()
{
int i;
ifstream f ("data.txt");
f >> i;
double x_0= 1.00;
double x_100 = l(x_0, i);
ofstream g ("results.txt", ios::app);
g <<"\n100th element (by looping): " << x_100;
x_100 = r(x_0);
g <<"\n100th element (by recursion): " << x_100;
return 0;
}
l() is iterative function,
r() is recursive function
double l(double x, int i)
{
for (int j = 0; j<i ; j++){
x = (x + 1)/(x+2);
}
return x;
}
double r(double x)
{
if (x == 0)
return 1;
else
return (r(x-1) + 1) / (r(x-1) + 2);
}
Here are the results
100th element (by looping): 0.618034
100th element (by recursion): 0.666667
I the recursive function you do
(r(x-1) + 1) / (r(x-1) + 2)
With x == 1.0 that's equal to
(r(1-1) + 1) / (r(1-1) + 2)
That's of course equal to
(r(0) + 1) / (r(0) + 2)
And since r(0) will return 1 that equation is
(1.0 + 1) / (1.0 + 2)
There's no further recursion. The result is 2.0 / 3.0 which is 0.66667.
The iterative function l on the other hand will do 100 iterations where each iteration will change the value of x, making it even smaller and smaller.
The functions simply does different things, leading to different results.
I'm trying to create a Vector3 struct but everytime I use the operator * it seems to throw an exception
"read access violation".
I'm relevantly new to c++ and have no idea what is causing this.
VS 2017, Debug, x86
Code
float x, y, z;
Vec3 operator+(Vec3 d) {
return { x + d.x, y + d.y, z + d.z };
}
Vec3 operator-(Vec3 d) {
return { x - d.x, y - d.y, z - d.z };
}
Vec3 operator*(float d) {
return { x * d, y * d, z * d }; // throwing an exception
/*
Unhandled exception thrown: read access violation.
this was 0x302C.*/
}
void Normalize() {
while (y < -180) {
y += 360;
};
while (y > 180) {
y -= 360;
};
if (x > 89) {
x = 89;
};
if (x < -89) {
x = -89;
};
}
};
// example code
uintptr_t c= *(uintptr_t*)(ModuleHandle+ 0x2);
Vec3* b= (Vec3*)(c+ 0x1);
Vec3 a= *b* 2;
You have a star before b:
Vec3 a= *b* 2;
Edit in regards to edited question, the other line of code above it seems to be the issue now:
Vec3* b= (Vec3*)(c+ 0x1);
If c isn't an array of at least 2 properly initialized Vec3 instances, dereferencing that is going to cause the access violation you're seeing.
And I mean literally of Vec3* or Vec3[] type, not a char* or something. Because you're adding 1 to it, the type of the array has to be of the type of an individual item so the CPU knows how much to move the pointer forward by.
I'm writing a templated matrix class using C++14. This class has three template parameters: the type of data stored (dtype), the number of rows (N) and the number of columns (M).
The class signature is
template<class dtype, size_t N, size_t M>
class Matrix
I've written a determinant member function that calls specific cases when a template parameter has a certain value. For example, when the number of rows is 1 it returns a copy of the matrix itself. Alternatively, when the number of rows is 2 or 3 it returns a 1x1 matrix of the same datatype with the determinant. Finally, when the number of rows is more than 3 it uses a recursive method to calculate the determinant based on the cofactor expansion of the determinant.
I am doing this as an exercise to better learn C++14 so I'd be very grateful for some help.
The code snippet causing issues is this part right here:
Matrix<dtype, 1, 1> det() const {
if (N != M || N >= 12) {
return Matrix<dtype, 1, 1>();
} else if (N == 1) {
return this->copy();
} else if (N == 2) {
return Matrix<dtype, 1, 1>(this->get(0, 0) * this->get(1, 1) - this->get(0, 1) * this->get(1, 0));
} else if (N == 3) {
return Matrix<dtype, 1, 1>(
this->get(0, 0) * (this->get(1, 1) * this->get(2, 2) - this->get(1, 2) * this->get(2, 1)) -
this->get(0, 1) * (this->get(1, 0) * this->get(2, 2) - this->get(1, 2) * this->get(2, 0)) +
this->get(0, 2) * (this->get(1, 0) * this->get(2, 1) - this->get(1, 1) * this->get(2, 0)));
} else if (N < 12) {
Matrix<dtype, 1, 1> determinant;
Matrix<dtype, N - 1, N - 1> sub_matrix;
for (size_t i = 0; i < N; ++i) {
sub_matrix = this->drop_cross(i, i);
Matrix<dtype, 1, 1> sub_det(sub_matrix.det());
if (i % 2 == 0) determinant = determinant + (this->get(0, i) * sub_det);
else if (i % 2 == 1) determinant = determinant - (this->get(0, i) * sub_det);
}
return determinant;
}
}
This function is called by this code:
#include "lin_alg_classes.h"
int main() {
Matrix<double, 3, 3> test3(1.0, true);
std::cout << std::endl;
std::cout << test3.det();
return 0;
}
And gives the following output:
In file included from C:\Users\ekin4\CLionProjects\mt_grav\main.cpp:5:0:
C:\Users\ekin4\CLionProjects\mt_grav\lin_alg_classes.h: In instantiation of 'Matrix<dtype, 1ull, 1ull> Matrix<dtype, N, M>::det() const [with dtype = double; long long unsigned int N = 3ull; long long unsigned int M = 3ull]':
C:\Users\ekin4\CLionProjects\mt_grav\main.cpp:29:28: required from here
C:\Users\ekin4\CLionProjects\mt_grav\lin_alg_classes.h:132:31: error: could not convert 'Matrix<dtype, N, M>::copy<double, 3ull, 3ull>()' from 'Matrix<double, 3ull, 3ull>' to 'Matrix<double, 1ull, 1ull>'
return this->copy();
What I don't understand is why it is calling the N = 1 case when it should be calling the N < 12 case. I have checked braces, parentheses and semicolons, and they are all correct, but for the life of me I don't understand what is happening.
Pre c++17 (if constexpr) you can use SFINAE and enable/disable different versions of det() according the values of N and M.
Something like (sorry: not tested)
template <std::size_t A = N, std::size_t B = M>
std::enable_if_t<(A != B) || (A > 11U), Matrix<dtype, 1, 1>> det() const
{ return Matrix<dtype, 1, 1>(); }
template <std::size_t A = N, std::size_t B = M>
std::enable_if_t<(A == B) && (A == 1U), Matrix<dtype, 1, 1>> det() const
{ return this->copy(); }
// other cases
I got an error when compile the below code saying that "called object type 'double' is not a function or function pointer". Because 'position' is a 3d vector, so I was trying to access each element of the vector.
int k=1;
int m=1;
double x, y, z;
x=position.x;
y=position.y;
z=position.z;
for (int j = 3; j < 1000 ; j++)
{
x(j) = 2 * x(j-1) - x(j-2) + (delta_t * delta_t * (-1.0*k/m) * x(j-1));
}
You'll actually have to keep track of x(j), x(j-1), and x(j-2) all as separate variables (using the syntax x(j) is akin to calling a function x() with argument j, which is not what you want).
Try:
double xj, xj_m1, xj_m2;
xj_m1 = position.x;
xj_m2 = position.x;
for (int j = 3; j < 1000 ; j++) {
xj = 2 * xj_m1 - xj_m2 + (delta_t * delta_t * (-1.0*k/m) * xj_m1);
//Update xj_m2 and xj_m1 for the next iteration
xj_m2 = xj_m1;
xj_m1 = xj;
}
When you do it:
x=position.x;
You expect that position.x is an array?
To access to an element in a vector, you can use the [] operator:
std::vector<int> myIntVector = { 1, 2, 3 };
int i = myIntVector[0]; // i = 1 because myIntVector[0] is the first element of myIntVector
The variable position looks like a coordinate vector, so it's not an array, it's just a class / struct like this:
struct Vector3
{
double x, y, z;
};
In other words, position.x is just a number.
I have a function that generates a lattice of prices and a function that uses that lattice to price the associated option. The generate_lattice function dynamically allocates space for an array, and a pointer to that array is returned. This pointer is what is passed to price_from_tree. Here is the code:
#include <iostream>
#include <math.h>
using std::cout;
using std::endl;
using std::max;
using std::nothrow;
double* generate_lattice(double asset_price, double u, double d, int periods)
{
int nodes = (periods * (periods + 1)) / 2; //Number of nodes = sum(1, # of periods)
double * lattice;
lattice = new (nothrow) double[nodes];
double up, down;
int price_index = 0;
for (int period = 0; period < periods + 1; period++) {
for (int exp = 0; exp < period + 1; exp++) {
up = pow(1 + u, exp);
down = pow(1 - d, period - exp);
lattice[price_index] = asset_price * up * down;
price_index++;
}
}
return lattice;
}
double price_from_tree(double* lattice, int periods, double strike, double risk_free, double period_len_years, bool euro = true, bool call = true)
{
int num_prices = ((periods + 1) * (periods + 2)) / 2;
double asset_max = lattice[num_prices - 1];
double asset_min = lattice[num_prices - (periods + 1)];
double asset_t0 = lattice[0];
double u = pow(asset_max / asset_t0, pow(periods, -1));
double d = pow(asset_min / asset_t0, pow(periods, -1));
double p = (exp(risk_free * period_len_years) - d) / (u - d);
double p_minus1 = 1 - p;
int start_node;
if (euro == true) { start_node = num_prices - periods - 1; }
else { start_node = 0; }
int sign;
if (call == true) { sign = 1; }
else { sign = -1; }
for (int node = start_node; node < num_prices; node++) {
lattice[node] = max(sign * (lattice[node] - strike), 0.0);
}
int price_index = num_prices - 1;
double pv_mult = exp(-risk_free * period_len_years);
double down_payoff, up_payoff, prev_payoff;
for (int period = periods + 1; period > 0; period--) {
for (int node = 0; node < period - 1; node++) {
down_payoff = lattice[price_index - (node + 1)];
up_payoff = lattice[price_index - node];
prev_payoff = pv_mult * (p * up_payoff + p_minus1 * down_payoff);
if (euro == false) {
prev_payoff = max(lattice[price_index - (node + 1) - (period - 1)], prev_payoff);
}
lattice[price_index - (node + 1) - (period - 1)] = prev_payoff;
}
price_index -= period;
}
return lattice[0];
}
int main(int argc, char** argv)
{
double* lattice = generate_lattice(100, 0.10, 0.10, 2);
double option1 = price_from_tree(lattice, 2, 105, 0.05, 1, true, true);
cout<<"option 1: "<<option1<<endl;
double* lattice2 = generate_lattice(100, 0.10, 0.10, 2);
return 0;
}
When I run the code, I get this output:
option 1: 8.28214
test: malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct
malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size)
= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t)))
- 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
Aborted
------------------
(program exited with code: 134)
All I can find on error 134 is descriptions along the lines of The job is killed with an abort signal. The code returns the correct value for price_from_tree in every case I've tried, but if I include multiple calls to generate_lattice it fails with the stated error. Is there a problem with my price_from_tree function that causes confusion within memory? Am I better off using vectors in this case?
You're corrupting your heap pretty badly. If you run with valgrind (assuming you're on a Linux machine) there are tons of errors.
==23357== Invalid write of size 8
==23357== at 0x400B9E: generate_lattice(double, double, double, int) (so.cpp:21)
==23357== by 0x400FC4: main (so.cpp:68)
==23357== Address 0x595b058 is 0 bytes after a block of size 24 alloc'd
==23357== at 0x4C27FFB: operator new[](unsigned long, std::nothrow_t const&) (vg_replace_malloc.c:325)
==23357== by 0x400B1A: generate_lattice(double, double, double, int) (so.cpp:14)
==23357== by 0x400FC4: main (so.cpp:68)
Your math is off. In generate_lattice, price_index grows beyond (periods * (periods + 1)) / 2. Try:
int nodes = ((periods+1) * (periods + 2)) / 2; //Number of nodes = sum(1, # of periods + 1)
The calculation of the index into the shared 1-dimensional array, lattice is inconsistent across the two functions:
(periods * (periods + 1)) / 2; // generate_lattice
((periods + 1) * (periods + 2)) / 2; // price_from_tree
This could be the source of the related malloc error.
generate_lattice creates an array of size n*(n+1)/2, but then initializes (n+1)*(n+1) elements of this array, right? That is probably corrupting the heap or something weird like that.
I didn't look at price_from_tree but if you're just using lattice as an array I doubt it causes a problem (unless you go off the end).
You're calculating the number of nodes incorrectly, and so you're running off the end of the array. Try it with periods = 2. Because you're doing < periods+1, you have to calculated nodes as (periods+1)*(periods+2)/2