Send the matrix from class to another class - c++

I have a class that has a matrix
class A{
private:
int matrix[10][5];
};
Also I have other class with method that get matrix and do with it
class B{
public:
void method(/*What to write here?*/){...}
};
So, help to releaze the syntax. How to take matrix from class and send it to other class?

Pass by reference
void method(A& a){...}
If method doesn't need to modify a then pass by const reference
void method(const A& a){...}
Based on the comments below it seems you want something like this
class A
{
public:
void set_coordinates(...) { matrix[...][...] = ...; }
private:
int matrix[10][5];
};
class B
{
public:
void method(A& a) { a.set_coordinates(...); }
};
i.e. pass the object A to method B::method but add sufficient public methods to A so that B can do the work it needs to do. This is what encapsulation is all about.

You can use vector<vector<int> >. That way you can pass them around. Or you can use friend classes, or use double pointers. Let me know if you want any of these I can provide examples.
Using double pointers:
#include <iostream>
using namespace std;
class A{
private:
int **matrix;
public:
A()
{
// since 2D array is array of arrays,
// double pointer is a pointer to array of pointers
// define the matrix, first make matrix point to an array of pointers
matrix = new int*[10];
// now make each element of pointer array
// which is a pointer point to actual array
for(int i=0;i<10;i++)
matrix[i] = new int[5];
// initialize like simple 2D array (another function maybe)
for(int i=0;i<10;i++)
for(int j=0;j<5;j++)
matrix[i][j] = i+j;
}
// note the return-type
int ** getMatrix()
{
return matrix;
}
};
class B{
public:
// wherever you want to access matrix, pass the double pointer
void method(int **matrix){
for(int i=0;i<10;i++)
for(int j=0;j<5;j++)
cout << matrix[i][j] << endl;
}
};
int main() {
// create objects
A a;
B b;
// pass the double pointer to B's method
b.method(a.getMatrix());
return 0;
}

Related

Create a heap-based 2D array without using double pointer syntax?

I need to declare a 2D array as the member variable of a class. I can't use STL (so, no vector), and I've been asked to avoid double/triple pointers. I want to be able to reference elements in this 2D array using subscripting notation, e.g. arr[0][0]. The array also must be declared on the heap due to its size.
Due to the requirements I have, none of the existing answers on StackOverflow meet my needs.
What I've been trying to do is:
class MyClass {
public:
MyClass() : arr(new int[1000][2]) {}
// other stuff here
private:
int arr[1000][2];
};
The error I get after compiling that class is "cannot initialize a parameter of type int * with an lvalue of type int[1000][2]". Clearly, I can solve this by using pointer syntax, but, as mentioned above, I've been asked to use "array syntax" for code clarity. I was hoping someone with a better understanding of C++ could explain how to use "array syntax".
Of course you can do this without double/triple pointers. You can even do this without use of any pointers in the class declaration. But first lets look at the more common approach. A 2D array is a simple extension of a 1D array.
Starting off with the standard way this is done for a 1D array of 1000 ints w/o using vector. The pointer, arr, is on the stack but points to an array of 1000 ints on the heap.
class MyClass {
public:
MyClass() : arr(new int[1000]) {}
private:
int *arr;
};
Elements are accessed the usual way. For instance arr[0]=42;
Extending this to a 2D array in the heap is a simple extension of the above.
You need to declare the member variable as a pointer to a 1D array instead of the basic type.
class MyClass {
public:
MyClass() : arr(new int[1000][2]) {}
private:
int (*arr)[2];
};
Similarly, you can refer to elements of the 2D array the usual way: arr[0][0]=42;
Finally, there is the approach that completely eliminates pointers except the one required for the new. Here we initialize a reference. The trick is to add a third level to new, the [1] so that the *new returns an object that is the actual 2D int array. Structurally, it is no different than what the pointer version above does but lets us directly initialize a reference to a 2D int array. It's certainly not a common idiom so I'd stick with the ptr approach.
class MyClass {
public:
MyClass() : arr(*new int[1][1000][2]) {}
~MyClass() {delete[] arr;}
//private: // to test
int(&arr)[1000][2];
};
int main()
{
MyClass obj;
obj.arr[2][1] = 42;
}
When your class has an array in it, and you use new to create a new instance of that class, that array is on the heap. You can still access the array with arr[i][j].
Why not do something like this?
class myClass {
public:
int arr[1000][2];
};
int main() {
myClass* test = new myClass;
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 2; j++) {
test->arr[i][j] = 5;
}
}
}
You can use 2 classes to achieve this.
class BaseArray {
public:
int& operator[](int x) { return this->arr[x]; }
int operator[](int index) const { return this->arr[index]; }
int arr[2];
};
class myClass {
public:
myClass() {}
~myClass() {}
BaseArray& operator[](int index) { return this->arr[index]; }
BaseArray operator[](int index) const { return this->arr[index]; }
BaseArray arr[1000];
};
Optionally use can use templates to make this class more dynamic.
template<class TYPE, int arraySize>
class BaseArray {
public:
TYPE& operator[](int x) { return this->arr[x]; }
TYPE operator[](int index) const { return this->arr[index]; }
TYPE arr[arraySize];
};
template<class TYPE, int dim1, int dim2>
class myClass {
public:
myClass() {}
~myClass() {}
BaseArray<TYPE, dim2>& operator[](int index) { return this->arr[index]; }
BaseArray<TYPE, dim2> operator[](int index) const { return this->arr[index]; }
BaseArray<TYPE, dim2> arr[dim1];
};
int main()
{
myClass<int, 1000, 2> myArray;
}
EDIT
When you provide the array dimentions int arr[1000][2]; the variable will automatically be allocated in the stack. If the array needs to be fully dynamic, you can just use a double pointer int** arr = { nullptr }; and initialize it at the constructor as shown below.
class myClass {
public:
myClass()
{
arr = new int* [1000];
for (int i = 0; i < 1000; ++i)
arr[i] = new int[2];
}
~myClass()
{
/* Make sure to delete or else it might flag a memory error. */
for (int i = 0; i < 1000; ++i)
delete[] arr[i];
delete[] arr;
}
int** arr = { nullptr };
};

How to store a reference to a C-style array in a class?

class Class
{
public:
Class(array[3][3]) //the constructor
{
this->array = array
}
array[3][3];
};
int main()
{
array[3][3] = {...initialization...};
Class object(array[3][3]);
}
I want to make an object, which uses the 2d array and modifies it. I know that C arrays are just pointers to an address, but I couldn't pass it in the constructor no matter how many *, & or [] I write.
The most clever thing I could think of is making an array of POINTERS in the class, and assigning each pointer, to the address of the original array's element via for loop, but then every time I want to modify, or read from the array in main, I have to write for example *array[2][1] = 3.
Any clever solution?
If I finally got the question correctly, you can use a reference to an array:
struct Class {
Class(int (&array)[3][3]) : array_(array)
{}
void set11(int value) {
array_[1][1] = value;
}
int (&array_)[3][3];
};
int main() {
int array[3][3]{};
Class object(array);
object.set11(99);
std::cout << array[1][1]; // Prints 99
}
If that's not what you want, please clarify your question.
Here's how to declare a pointer in your class that can point to the array in main.
class Class
{
public:
Class(int (*array)[3])
{
this->array = array;
}
int (*array)[3];
};
int main()
{
int array[3][3] = { ... };
Class object(array);
}

access a class member based on a string

i want to write a function which takes in a vector of objects and name of one of their property. then it will do some manipulation based on the values of that property of the objects.finally will return an object.
eg.
class A{
Point center;
int length;
...
...
};
class B{
Point position;
bool value;
...
...
};
now if we pass the function a vector of type A, it should manipulate the objects based on the value of center; if we pass the function a vector of type B, it should manipulate the objects based on values of position.
functiona(vector<T>,string property)
inside the function how can i access a property based in the passed string property??
EDIT: the 2nd property being string is just for illustration; i don't care what type it is
Yes, it can be done using pointers-to-members. Example use:
#include <iostream>
#include <vector>
using namespace std;
class A {
public:
int a;
A(int x):a(x){}
};
class B {
public:
int b;
B(int x):b(x){}
};
template <typename T> int func(vector<T> data, int T::*pointer) {
int total = 0;
for (unsigned i = 0; i < data.size(); ++i) {
total += data[i].*pointer;
}
return total;
}
int main() {
vector<A> vec1;
vec1.push_back(A(123));
vec1.push_back(A(456));
vec1.push_back(A(789));
vector<B> vec2;
vec2.push_back(B(666));
vec2.push_back(B(666));
vec2.push_back(B(666));
cout << func(vec1, &A::a) << endl;
cout << func(vec2, &B::b) << endl;
return 0;
}
You declare a pointer-to-member as such: valueType class::*pointerName, read adresses as such: &class::field and use them like that: object.*pointerToMember or pointerToObject->*pointerToMember.

Multidimensional array assignment

if you look at this class, how do I achieve the following:
class foo {
public:
void foo(double (&arr)[3][4]) { //Constructor
arr2 = arr; //??? How to assign multidimensional arrays?
}
void bar() { //Usage
double doSomething = arr2[1][0];
}
private:
double* arr2[3][4]; //??? How to store this?
}
Thanks everyone!
More explanation: This should be a class, that get a reference to a two-dimensional array in its constructor (foo()). It stores this reference in a member variable, so that some other function (bar()) can access them later.
So what "format" has the member variable and how do I assign the parameter of the constructor to it?
Edit2: As I impement an interface, I can't change signatures to use std::vector>...
class foo {
public:
// See http://cdecl.ridiculousfish.com/?q=double+%28%26arr%29%5B3%5D%5B4%5D
foo(double (&arr)[3][4]) :arr2(&arr) {
// This constructor uses constructor list initialization, but you could have used
// assignment instead, like this:
// arr2 = &arr;
}
double bar() { //Usage
double doSomething = (*arr2)[1][0];
return doSomething*doSomething;
}
private:
// See http://cdecl.ridiculousfish.com/?q=double+%28*arr2%29%5B3%5D%5B4%5D
double (*arr2)[3][4];
};
int main () {
double oof[3][4] = {{0.,},};
foo moo(oof);
return int(moo.bar());
}
Since you don't specify a reason for using raw pointers and this is tagged C++, you should use nested vectors instead:
#include <vector>
class foo
{
public:
void foo(const std::vector<std::vector<double>>& arr)
: arr2(arr)
{ //Constructor
}
void bar() { //Usage
double doSomething = arr2[1][0];
}
private:
std::vector<std::vector<double>> arr2;
};

C++ / Arduino: dynamic int array

I'm writing a class for the Arduino. It's been going well so far, but I'm sort of stuck now...
I have declared an int array in my class
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
When I initialize the class MyClass myClass1(5) I need the array to look like this {0,0,0,0,0}.
My question: what do I need to do so that the array contains 'size' amount of zeros?
MyClass::MyClass(int size)
{
//what goes here to dynamically initialize the array
for(int i=0; i < size; i++) _intArray[i] = 0;
}
Edit: Following up on various replies below, Arduino does not include the standard library so unfortunately std::vector is not an option
Your code as I'm writing this:
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
The declaration of _intArray is not valid C++: a raw array needs to have a size specified at compile time.
You can instead instead use a std::vector:
class myClass
{
public:
MyClass( int size )
: intArray_( size ) // Vector of given size with zero-valued elements.
{}
private:
std::vector<int> intArray_;
};
Note 1: some compilers may allow your original code as a language extension, in order to support the "struct hack" (that's a C technique that's not necessary in C++).
Note 2: I've changed the name of your member. Generally underscores at the start of names can be problematic because they may conflict with names from the C++ implementation.
Cheers & hth.,
You should use a std::vector.
class myCLass {
public:
myClass(int size)
: intarray(size) {
for(int i = 0; i < size; i++) intarray[i] = 0;
}
private:
std::vector<int> intarray;
};
You should really use vectors as others have suggested. A work-around could be as shown (in case you do not want to use memcpy or a loop).
This would be useful if you have a really huge array. Note that it would add a level of indirection to access the array.
class myClass
{
public:
myClass(){
mt = T(); // value initialize.
}
private:
struct T{
int _intArray[10];
} mt;
};
int main(){
myClass m;
}
I'll try the following:
class myClass
{
public:
MyClass(int size);
~MyClass();
private:
int* _intArray;
};
MyClass::MyClass(int size) {
_intArray = new int[size];
for (int i=0; i<size; ++i) _intArray[i] =0; // or use memset ...
}
MyClass::~MyClass() {
delete[] _intArray;
}
Or, even better, use a STL vector instead ...
you can use another hack basing on a string value and then populate a limited size array
check this :
https://github.com/Riadam/ViewPort-Array-Shifter-for-Arduino-Uno.git