c++ class constructor for array - c++

I am writing a Matrix2D class. At the beginning I was using constructor as folows,
My code:
Matrix2D(float a,float b, float c,float d)
{
a_=a;
....
}
However, I have just realized that it would be a lot better if I could use multi dimensional array [2][2]. That's where the problem lies,
How do I write constructor for array ?
class Matrix
{
float matrix[2][2];
public:
Matrix2D(float a,float b,float c, float d)
{
matrix[2][2]={a,b,c,d} // not valid
}
}
Just to let you know, I don't ask for a complete code.
I just need someone to put me on a right track.

For C++11 you can do:
Matrix(float a,float b,float c, float d) :
matrix{{a,b},{c,d}}
{
}
There's no clean alternative for C++03.

matrix[0][0] = a; // initialize one element
and so on.

matrix[0][0] = value you want to matrix [n][n] = value you want but count up in a loop
so the matrix can be dynamic in size or you can reuse your code later.
for(int ii(0); ii < first dimension size; ++ii)
{
for(int ll(0); ii < second dimension size; ++ll)
{
matrix[ii][ll] = value you want;
}
}
this will make your code more extensible and more useful outside of this application and maybe it's not useful or maybe it is.

If it will be a matrix 2X2, then you can pass a float array and then loop through it.
for example
for(int x = 0;x<4;x++)
{
matrix[0][x] = myarray[x];
}

Luchian's version is best if you have a C++11 compiler. Here's one that works for all versions of C++:
struct matrix_holder { float matrix[2][2]; };
class Matrix : matrix_holder
{
static matrix_holder pack(float a,float b,float c, float d)
{
matrix_holder h = { {{a, b}, {c, d}} };
return h;
}
public:
Matrix(float a,float b,float c, float d) : matrix_holder(pack(a,b,c,d))
{
}
};
The optimizer will inline away the helper.

Related

C++ Using member functions from a similar virtual public class

Suppose I have a bunch of inherited classes like this:
...and they all serve the purpose of making all sorts of polynomials. Class X is mainly a variable tank, classes A, B, etc are all virtual public X and each creates ont type of polynomial, class Y makes the calls. Besides A and B, any other class can be added.
Now, everything works but for a newly added "virtual public" class I need to reuse some member function(s) from other classes, here from A inside class B. I tried to make the simplest example:
#include <iostream>
#include <cmath>
#include <functional>
// variable tank
class X
{
protected:
// general variables
double *m_c;
int m_n;
double m_w;
// funcX related
double m_r;
int m_i {0};
public:
~X() = default;
/* Simple bracketed root-finding. This is called from more than
* one "virtual public" classes.
*/
const double funcX(const double &x, const double &y, \
std::function<const double(const double&, const int&)> fp, \
const int &k)
{
double a {x}, b {y}, fmid;
while (m_i<100)
{
m_r = 0.5*(a + b);
fmid = fp(m_r, k);
if (fabs(b-a) <= 1e-3)
break;
if (fmid < 0)
b = m_r;
else
a = m_r;
++m_i;
}
return m_r;
}
};
// one of the many classes that generate polynomials
class A: virtual public X
{
public:
void funcA(const int &n)
{
// set order
m_n = n;
// calculate X::m_c[i]
m_c = new double[m_n+1];
for (short i=0; i<=m_n>>1; ++i)
{
int sgn {i%2 ? -1 : 1};
m_c[i<<1] = sgn/((i + 1.0)*(i + 1.0));
}
// The polynomial is zero somewhere, use funcX() to find where.
m_w = funcX(5.0, 0.0, \
[this](const double &x, const int &n) \
{ return calcA(x, n); }, \
m_n);
}
// calculates the value of the polynomial of order n, at x
const double calcA(const double &x, const int &n) const
{
double out {static_cast<double>(m_c[0])};
for (short i=1; i<=n; ++i)
out = m_c[i] + x*out;
return out;
}
};
class B: virtual public X
{
private:
A m_a; // otherwise the lambda function does not "catch" it
public:
void funcB(const int &n)
{
// same as in A
m_n = n;
// same as in A, calculate coefficients
m_c = new double[m_n+1];
for (short i=0; i<=m_n; ++i)
{
int sgn {i%2 ? -1 : 1};
m_c[i] = sgn/((i + 1)<<1);
}
/* Here I need A::calcA(). Instead of duplicating the code,
* I want to call it through X::funcX(). The code compiles,
* but it crashes.
*/
m_w = funcX(0.5, 1.0, \
[this](const double &x, const int &n) \
{ return m_a.calcA(x, n); }, \
m_n);
}
const double getW() const { return m_w; }
};
class Y: public A, public B
{
public:
Y(const int &n, const int &i)
{
// call one of the "virtual public" classes through i
switch (i)
{
case 1: funcA(n); break;
case 2: funcB(n); break;
}
}
void printC() { for (short i=0; i<=m_n; ++i) std::cout << m_c[i] << '\n'; }
void printW() { std::cout << m_w << '\n'; }
void printA(const double &x, const double &n) { std::cout << A::calcA(x, n) << '\n'; }
};
int main(int argc, char *argv[])
{
int N {6};
Y *y;
for (short i=1; i<=2; ++i)
{
y = new Y(N, i);
y->printC();
y->printW();
y->printA(1.2, N);
}
return 0;
}
class X:
X::funcX() is a simple root-finding algorithm which gets called in more than one virtual public classes (A, B, etc). m_c, m_n, m_w are shared variables.
classes A and B:
their main function is funcA() (and funcB(), and so on) and it creates the polynomial (in the body, there's a for loop), based on the calculated order, X::m_n. Evaluating the polynomial is A::calcA(). This needs to be either called by class B, too, or redefined. I'd rather avoid the latter because of the code bloating. It also doesn't look very "professional" for my fairly beginner level...
class Y
This calls any of the virtual public classes based on argument i (the switch/case).
The code compiles, but crashes. It prints the case for. This example points to A::funcA() as the culprit, but in the original program I can see that the coeficients, m_c[i], are not even initialized with dynamic memory, as in trying to print out m_c[0] crashes. I tried moving the new double[] insode the function in A, but that doesn't work.
I don't know how to make it. Does this make sense, is it possible? If yes, how?
Edit: Forgot to add that I can't just move calcA() from A to the top, in X, because each polynomial is evaluated differently, as in there are shortcuts, changes, in every one that makes it possible to have different, optimized evaluations for each polynomial. I could make X::calcA() a universal one, but there will be a performance penalty, which I'd rather not pay.
It seems that your problem is induced by problems with design. When you need to use methods from other class that may mean:
The is a problem with "single responsibility" principle. Class does too much. For example numerical equation solving algorithms are self-sufficient entities and shouldn't be part of polynomial. They can work with any polynomial.
There is a problem with inheritance tree. For example a common ancestor should be created and that common methods should be in it. Note, that if you can't find short and understandable name for that ancestor, then this is not the solution.
Inheritance is not used properly. For example I can't see virtual methods in your code which is strange.
Let's get closer to your example. You are using virtual multiple inheritance which is considered to be very heavy pattern and usually should not be used. Moreover, there are no virtual methods in your code, so you actually do not use inheritance at all. You either must drop inheritance, or think of common methods which make sense for all your classes. For functions this seems to be an ability to calculate function value in specified point. Then move all code, that is not describing polynomials or functions out of the classes. Move out numerical solvers. This will allow to reuse them for all your classes, that support needed interface. Get rid of Y class at all. It seems, that it is needed to emulate virtual methods with switches and enums. You don't need it, rename funcA and funcB just to func if they are semantically the same and do the same thing for different types of polynomials.

C++ How to treat an array of classes as an array of primary types?

I have this code:
class Vector3
{
public:
Vector3() : x(values[0]), y(values[1]), z(values[2])
{ x = y = z = 0; }
float& x;
float& y;
float& z;
private:
float[3] values;
};
class Model
{
public:
Vector3 vertices[64];
};
I'm doing this vector class because I want to deal with the values as X, Y, Z in the code, but for some operations I need a contiguous array of values to be passed to a function.
So the whole array of vertices[64] need to be [x0][y0][z0][x1][y1][z1][x2][y2][z2] etc.
But if I do this:
//Get first address:
void* firstAddress = &vertices[0];
//Or
void* firstAddress = vertices;
I don't have the contiguous array as I need it (the data is all messed up), and I'm guessing it's because of the pointers I have in the Vector3 class.
Is there any way I can do get this functionality that I want? (Having a single array of float but dealing with values as x,y,z)
Firstly, the Standard doesn't define how references should be implemented, but they'll almost certainly occupy actual memory in your class much a pointer members would, ruining the contiguous data packing you're hoping for....
If your focus is more on the vertices container, and you just want x/y/z member access to elements in it, then you could try something like:
template <size_t N>
class Vertices
{
public:
class Proxy
{
public:
Proxy(float* p) : x(p[0]), y(p[1]), z(p[2]) { }
float& x;
float& y;
float& z;
};
Proxy operator[](size_t n) { return Proxy(&d_[n * 3]); }
const Proxy operator[](size_t n) const { return Proxy(&d_[n * 3]); }
private:
float d_[N * 3];
};
You could have member functions instead:
class V3
{
float data[3];
public:
V3() : data{0,0,0} {}
float & x() { return data[0]; }
float & y() { return data[1]; }
float & z() { return data[2]; }
};
You could also omit the constructor and have an aggregate, if that's more suitable.
What you have and array of values pointers (pointing to arrays of 3 floats) with 3 float references (x, y, z). You probably ant something more like:
float & x() { return values[0]; }
float & y() { return values[1]; }
float & z() { return values[2]; }
If I understand your requirement for continuous data in the Model, then your Vector is really an alias to a specific triple of data in the model. No float storage required.
class Model
class Vector
Vector(Model *model_, size_t idx_) : model(model_),idx(idx_) { };
Model *model;
size_t idx;
float & x() { return model->data[3*idx]; }
float & y() { return model->data[3*idx+1]; }
float & z() { return model->data[3*idx+2]; }
float data[64 * 3];
Vector vectors[64];
Model() {
...
for( size_t ii = 0; ii < 64; ii++ ) {
vectors[ii] = new Vector(this,ii);
}
Vector & vector(size_t idx) { return vectors[ii]; }
For a guaranteed contiguous array you need to either copy the data into the array, or use compiler-specific guarantees about memory layout, in particular that
there will be no padding,
and if you want to also access triplets of the array as Vector3 instances, that
accessing a Vector3 at arbitrary address will not cause a trap or inefficiency (we're into alignment here).
It so happens that some common libraries such as OpenCV do make such assumptions for their internal image buffers.
But I'm not entirely sure that the code I've seen has not been platform-adapted. So, in practice you have these choices:
copy the data contiguously to an array (or from it), and/or
use an existing library that provides this kind of functionality, such as OpenCV.
Note that using member functions instead of references buys you nothing wrt. to the contiguous array problem, but it does make the Vector3 potentially assignable.
On further reflection, i was maybe too trigger-happy writing the above. For if you can guarantee total size 3*sizeof(float), and that's almost a given (just get rid of those references), then you are guaranteed that you can access a Vector3 at any address that can hold a float, since C++ guarantees arrays with no padding, and since in such an array a Vector3 can end up at any address that can hold a float. So the in-practice problem reduces to making a decision about supporting compilers or compiler configurations that are unable to make Vector3 of size 3*sizeof(float).
I.e.
struct Vector3
{
float x, y, z;
auto operator[]( int i ) -> float& { return (&x)[i]; }
auto operator[]( int i ) const -> float const& { return (&x)[i]; }
};
static_assert( sizeof( Vector3 ) == 3*sizeof( float ), "Ungood Vector3 size" );
using the fact that members with no intervening access specifier are guaranteed to be in increasing address order.
Disclaimer: off the cuff code, not touched by compiler's hands.
If you keep your Vector3 class a POD you should be able to simply cast your vertices to a float array:
struct Vector3 {
float x;
float y;
float z;
};
class Model
{
public:
Vector3 vertices[64];
float* data() {
return reinterpret_cast<float*>(vertices);
}
};
int main() {
Model m;
for(int i = 0; i < 64; ++i) {
m.vertices[i] = {10+i,100+i,1000+i};
}
float *data = m.data();
for(int i= 0; i < 64*3; ++i) {
std::cout << data[i] << ", ";
}
}
Only problem could be the Allignment of the structure, but should you use c++11, there is a standard way of alligning the structure, using allignasalignas(alignof(float[3])). I don't know if this is really required.
Also, c++11 gives quite a few options on what to do with Vector3, while still considering it as a POD type.

How to evaluate a function directly?

Title may not make any sense but I dont really know how to explain this.
I have a class called polynomial and lets say I defined a polynome called p1 which is 2x+4. What I want to do is calculate p1(5) directly. I dont want anything like double calculate (polynomial) etc I want to be able to calculate my polynom with p1(x).
I hope my question is clear
Overload the function-call operator:
struct polynomial
{
double a, b;
polynomial(double m, double n) : a(m), b(n) { } // represents "a * x + b"
double operator()(double x) const
{
return a * x + b;
}
};
Usage:
polynomial p(2.5, 3.8);
double val = p(1.0);
By overloading operator() you can "call" an object just like you would call a function:
struct polynomial {
int operator()(int x)
{
/* calculate */
}
};
int main()
{
polynomial p;
int x = p(5);
}

C++ how call template's class constructor

I have such piece of code:
template <class T>
struct Rgb
{
T *r, *g, *b;
Rgb(int nr, int ng, int nb)
{
r = new T(nr);
g = new T(ng);
b = new T(nb);
}
Rgb(int n)
{
Rgb(n, n, n);
}
~Rgb()
{
delete r;
delete g;
delete b;
}
};
I have done it in such way, because I want to be able to create objects like:
Rgb<std::vector<int>> a(10); // so it creates 3 vectors inside,
// each with 10 elements or
Rgb<std::deque<double>> a(2, 5, 4); // so it creates 3 deques inside
// with different sizes
But the implementation I have given above does not work. Help me please... thanks...
If you compiler supports constructor delegation (which e.g. Clang 3.2 does) you can do the following:
Rgb(int n) : Rgb(n, n, n)
{
}
What you're doing is constructing a temporary Rgb instance in the constructor, which will fail once the uninitialized r, g and b get deleted.
Otherwise I'd recommend either creating a common init function that does the initialization or simply duplicate the code. And as the comments are noting you shouldn't use new here (that's almost always a code smell in modern C++ code). Bringing this together:
template <class T>
struct Rgb
{
T r, g, b;
Rgb(int nr, int ng, int nb) : r(nr), g(ng), b(nb)
{ }
Rgb(int n) : r(n), g(n), b(n)
{ }
~Rgb()
{ }
};

Multi-dimensional array

I need to create a function that has a parameter which is a multi-dimensional array with two dimensions being user-specified, e.g.
int function(int a, int b, int array[a][b])
{
...
}
How would I do that in C++ ?
Are the dimensions known at compile-time? In that case, turn them into template parameters and pass the array by reference:
template<int a, int b>
int function(int(&array)[a][b])
{
...
}
Example client code:
int x[3][7];
function(x);
int y[6][2];
function(y);
Assuming the dimensions are not known at compile time, you emulate a two dimensional array with a one dimensional array:
int& getat(int x, int y, int r, int c, int *array) {return array[y*c+x];}
int function(int a, int b, int *array) {
getat(4, 2, a, b, array) = 32; //array[4,2] = 32
}
or, for safety, wrap it all in a class:
template <class T>
class array2d {
std::vector<T> data;
unsigned cols, rows;
public:
array2d() : data(), cols(0), rows(0) {}
array2d(unsigned c, unsigned r) : data(c*r), cols(c), rows(r) {}
T& operator()(unsigned c, unsigned r) {
assert(c<cols&&r<rows);
return data[r*cols+c];
}
};
or, best yet, use Boost's Multidimensional Array, which will be better than anything mere mortals could write.
I'm not sure if this work, because your question and code are not the same, according to your code the function can have 3 parameters, so this would work:
int function(int a, int b, int** &array)
{
array = new int*[a];
for (int i =0;i<a;i++)
array[i] = new int[b];
// I don't know why you are returning int, probably doing something here....
}
However your question says that your function can take only one parameter, so:
if the dimensions are known at compile time, then Fred's Answer is the best (it charmed me in fact! :) ).
if not, I can't see any possible solution that allows passing more than one user-specified value other than encapsulating all these values in one object.
Like this:
class Foo {
public:
Foo(int d1, int d2)
{ a = d1; b = d2; }
int a,b;
int** array;
};
int function(Foo &f)
{
f.array = new int*[f.a];
for (int i = 0;i<f.a;i++)
f.array[i] = new int[f.b];
// I don't know why you are returning int, probably doing something here....
}
Though I find it a bad idea, in fact the function could be a parameterless method instead:
class Foo {
public:
Foo(int d1, int d2)
{ a = d1; b = d2; }
void Create() // Or could do this right in the Constructor
{
array = new int*[a];
for (int i = 0;i<a;i++)
array[i] = new int[b];
}
private:
int a,b;
int** array;
};
Still this is a bad idea, because you are reinventing the wheel, as there are a perfect class in the STL to do all the work for you:
vector< vector<int> > v; // Now v is a 2D array