implement operator ‘[]’ for class ‘CMatrix’ - overloading

#include<iostream>
using namespace std;
class Array {
private:
int * data;
int size;
int isValidIndex();
public:
Array ( )
{
data = 0;
size = 0;
}
Array ( int );
Array (const Array &);
Array & operator = ( const Array & );
int & operator [] ( int );
void reSize(int);
~Array();
};
class CMatrix
{
private:
int * * data;
int row;
int col;
//isValidBounds( int , int );
public:
CMatrix ( )
{
data = 0;
row = col = 0;
}
CMatrix ( int r, int c );
CMatrix ( const CMatrix & );
CMatrix & operator = ( const CMatrix & );
//many other functions
};
//Do you feel suitable to implement operator ‘[]’ for class ‘CMatrix’ such that we should be able to manipulate them as follows, If yes then give the definition of operator ‘[]’ for ‘CMatrix’, otherwise given reason (solid/pinpoint) for not implementing this operator.
main()
{
CMatrix m(3,4); //3 by 4 matrix where ist row/col index is 0
m[1][2] = 67;
cout << m[1][2]; //should display 67
}

Related

proxy class in rvalue - how to implement assignment operator?

Suppose I have a simple vector class where elements are accessed through a proxy class.
Vector class:
class vec {
public:
vec(int len) {
length = len;
data = new double [len];
}
proxy operator[](int i) {
if (i >= 0 && i < length) {
return proxy(i, data);
}
else {
std::cerr << "AHHHH!\n";
exit(1);
}
}
private:
int length;
double * data;
};
Proxy class:
class proxy {
public:
proxy(int i, double * d) {
index = i;
data = d;
}
void operator=(double rhs) {
data[index] = rhs;
}
private:
int index;
double * data;
};
How can I assign elements from the vector (or rather, from the proxy) to a variable of type double? In other words, how do I accomplish the following:
int main() {
vec a(2);
double x = 3.14;
a[0] = x; // Works!
x = a[0]; // How to make work?
return 0;
}
Unfortunately, I can't write something like:
friend double operator=(double & lhs, const proxy & p) { ... }
since operator= must be a member.
Add a conversion function to your proxy class:
class proxy
{
public:
operator double() const { return data[index]; }
// ...
};

Rectangle Class and Templates C++

I'm trying to write a code that creates a rectangle class and also create two classes which compare the perimeter and the area of two rectangles and return the larger of the two. I keep getting errors that there is an expected ';' in places which I don't think they belong. Any suggestions?
#include <cstdlib>
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
template <typename Object, typename Comparator>
const Object & findMax( const vector<Object> & arr, Comparator isLessThan )
{
int maxIndex = 0;
for( int i = 1; i < arr.size(); ++i )
if( isLessThan( arr[ maxIndex], arr[ i ] ) )
maxIndex = i;
return arr[ maxIndex ];
}
class AreaComparator
{
public:
int compare( Rectangle lhs, Rectangle rhs ) const
{ return double.compare( lhs.getArea(), rhs.getArea() ); }
};
class PeriComparator
{
public:
int compare( Rectangle lhs, Rectangle rhs ) const
{ return double.compare( lhs.getPerimeter(), rhs.getPerimeter() ); }
};
class Rectangle
{
double length, width;
public:
Rectangle( double l, double w)
{
l = length;
w = width;
}
double getArea()
{
return length * width;
}
double getPerimeter()
{
return ( 2 * length) + ( 2 * width );
}
};
int main(int argc, char *argv[])
{
cout <<(findMax(new Rectangle[] { new Rectangle(1, 5), new Rectangle(2, 3) }, new AreaComparator())) << endl;
cout <<(findMax(new Rectangle[] { new Rectangle(1, 5), new Rectangle(2, 3) }, new PeriComparator())) << endl;
system("PAUSE");
delete Rectangle[];
delete AreaComparator[];
delete PeriComparator[];
return EXIT_SUCCESS;
}
Any suggestions?
Building on #Logicrat's comment, I would suggest assigning all your new objects to local variable names, and then splitting up your cout statements into shorter pieces (multiple short cout's replacing each long cout). If the ; problem persists, you will more easily see why.

How to balance style and efficiecny when accessing two-dimensional array, vector of vectors?

CObject below has vertex arrays and buffers and various other member variables. The question is, how should I access the data in CAgent from CAnotherClass especially with the two-dimensional array (currently vectors) concerning style and also efficiency within and near openGL ES rendering callback function. The vectors of sub-objects are normally reasonable but could get as large as 32,000.
class CObject
{
// vertex arrays, buffers, and data
int val;
public:
int GetValue(){ return val; }
void SetValue( int v ){ val = v; }
};
class CAgent
{
friend class CAnotherClass; // may I, since like an extension?
enum ObjType { a, b, c, };
std::vector< CObject * > m_Objects; // implementation fills these
std::vector< std::vector< CObject * > > m_SubObjects; // each object above has n sub-objects
// for option B below
CObject * GetSubObjectN( int type, int n ) { return m_SubObjects[type][n]; }
std::vector< CObject * > & GetSubObjects( int type ) { return m_SubObjects[type]; }
};
class CAgentSub : public CAgent
{
class CAnotherClass * m_AgentExtension; // really just an extension of this
void Render( double timestamp ); // implementation calls CAnotherClass::Render()
};
class CAnotherClass
{
CAgentSub * m_Agent;
CObject * m_CurrentObject; // for convenience
std::vector< CObject * > * m_CurrentSubObjects;
int m_ObjectType; // or this way
void SetObjectType( int type )
{
m_CurrentObject = m_Agent->m_Objects[type]; // for convenience
m_CurrentSubObjects = &m_Agent->m_SubObjects[type];
m_ObjectType = type; // or this way?
}
void DoSomethingInteresting()
{
int val = -1;
int startVal = 0;
// option A
for ( int n = 0; n < m_CurrentSubObjects->size(); ++n )
{
val = (*m_CurrentSubObjects)[n]->GetValue(); // this is what I'm doing but seems cumbersome
// and not that easy to read
(*m_CurrentSubObjects)[n]->SetValue( startVal );
}
// option B
for ( int n = 0; n < m_Agent->GetSubObjects(m_ObjectType).size(); ++n )
val = m_Agent->GetSubObjectN( m_ObjectType, n )->GetValue();
// option C
for ( int n = 0; n < m_Agent->m_SubObjects[m_ObjectType].size(); ++n )
val = m_Agent->m_SubObjects[m_ObjectType][n]->GetValue();
// option D
for ( std::vector<CObject *>::iterator it = m_Agent->m_SubObjects[m_ObjectType].begin();
it != m_Agent->m_SubObjects[m_ObjectType].end();
++it )
{
(*it)->SetValue( startVal );
}
// setting data at various indexes
int index = 23;
(*m_CurrentSubObjects)[index]->SetValue( startVal );
m_Agent->GetSubObjectN( m_ObjectType, index )->SetValue( startVal );
m_Agent->m_SubObjects[m_ObjectType][index]->SetValue( startVal );
std::vector<CObject *>::iterator nth = m_Agent->m_SubObjects[m_ObjectType].begin() + index;
(*nth)->SetValue( startVal );
}
void Render( double timestamp );
};

matrix in a class in C++

the following code is for three classes , class One, class Two, class Three.
class Three takes tow vectors, the first vector contains instances of One , the second vector contains instances of Two.
I want to get a 2D matrix via a method in Three , this matrix will have two equal indices each one is the size of the vector of One instances.
I don't know where to declare this matrix , and how to initialize it.
i will present a code is working fine before i declare the matrix , then i will present one example of my many tries which is not working and producing error messages.
here is the code before declaring the matrix(it works fine)
#include<iostream>
#include<vector>
#include <stdlib.h>
using namespace std;
const unsigned int N = 5;
class One
{
private:
unsigned int id;
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
One(unsigned int init_val = 0): id(init_val) {}; // constructor
~One() {}; // destructor
};
class Two
{
private:
One first_one;
One second_one;
unsigned int rank;
public:
unsigned int get_rank() {return rank;};
void set_rank(unsigned int value) {rank = value;};
unsigned int get_One_1(){return first_one.get_id();};
unsigned int get_One_2(){return second_one.get_id();};
Two(const One& One_1 = 0, const One& One_2 =0 , unsigned int init_rank = 0)
: first_one(One_1), second_one(One_2), rank(init_rank)
{
}
~Two() {} ; // destructor
};
class Three
{
private:
std::vector<One> ones;
std::vector<Two> twos;
public:
Three(vector<One>& one_vector, vector<Two>& two_vector)
: ones(one_vector), twos(two_vector)
{
}
~Three() {};
vector<One> get_ones(){return ones;};
vector<Two> get_twos(){return twos;};
void set_ones(vector<One> vector_1_value) {ones = vector_1_value;};
void set_twos(vector<Two> vector_2_value) {twos = vector_2_value;};
};
int main()
{
cout<< "Hello, This is a draft for classes"<< endl;
vector<One> elements(5);
cout<<elements[1].get_id()<<endl;
vector<Two> members(10);
cout<<members[8].get_One_1()<<endl;
Three item(elements, members);
cout<<item.get_ones()[3].get_id() << endl;
return 0;
}
now i declared a method to produce a matrix in Three , the method's name is get_Mat() here is the code :
#include<iostream>
#include<vector>
#include <stdlib.h>
using namespace std;
const unsigned int N = 5;
class One
{
private:
unsigned int id;
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
One(unsigned int init_val = 0): id(init_val) {}; // constructor
~One() {}; // destructor
};
class Two
{
private:
One first_one;
One second_one;
unsigned int rank;
public:
unsigned int get_rank() {return rank;};
void set_rank(unsigned int value) {rank = value;};
unsigned int get_One_1(){return first_one.get_id();};
unsigned int get_One_2(){return second_one.get_id();};
Two(const One& One_1 = 0, const One& One_2 =0 , unsigned int init_rank = 0)
: first_one(One_1), second_one(One_2), rank(init_rank)
{
}
~Two() {} ; // destructor
};
class Three
{
private:
std::vector<One> ones;
std::vector<Two> twos;
public:
Three(vector<One>& one_vector, vector<Two>& two_vector)
: ones(one_vector), twos(two_vector)
{
}
~Three() {};
vector<One> get_ones(){return ones;};
vector<Two> get_twos(){return twos;};
void set_ones(vector<One> vector_1_value) {ones = vector_1_value;};
void set_twos(vector<Two> vector_2_value) {twos = vector_2_value;};
unsigned int get_Mat() {
unsigned int mat[ones.size()][ones.size()];
for(unsigned int i = 0; i < ones.size(); ++i)
for(unsigned int j = 0; j < ones.size(); ++j)
mat[i][j] = 1;
return mat;}
};
int main()
{
cout<< "Hello, This is a draft for classes"<< endl;
vector<One> elements(5);
cout<<elements[1].get_id()<<endl;
vector<Two> members(10);
cout<<members[8].get_One_1()<<endl;
Three item(elements, members);
cout<<item.get_ones()[3].get_id() << endl;
return 0;
}
I will be very thankful if you can help me to find a way to produce this matrix via a method in class Three.
Thanks.
get_Mat returns an integer, not a matrix. It is better to use vector<vector<unsigned int> >, that will avoid a lot of troubles later on.
Or have a look here (c++):
Return a 2d array from a function
or here (C):
Return a 2d array from a function

unable to access function

I made a program for binary heap given below-
#include<iostream>
using namespace std;
/**
* Construct the binary heap.
* capacity is the capacity of the binary heap.
*/
class BinaryHeap
{
private:
int currentSize; // Number of elements in heap
int array[]; // The heap array
void buildHeap( );
void percolateDown( int hole );
public:
bool isEmpty( ) const;
bool isFull( ) const;
int findmini( ) const;
void insert( int x );
void deleteMin( );
void deleteMin( int minItem );
void makeEmpty( );
public :
BinaryHeap( )
{
currentSize = 0;
}
BinaryHeap( int capacity )
{
array[capacity + 1];
currentSize = 0;
}
};
int main()
{
int resp, ch, choice;
int n, i;
cout << "enter the size of heap" << endl;
cin >> n;
BinaryHeap b(int n);
cout << "enter the item " << endl;
cin >> ch;
b.insert( int ch);
return 0;
}
while compiling it gives errors
request for member 'insert' in 'b', which is of non-class type 'BinaryHeap(int)'
and
expected primary-expression before 'int'
why is this happening and how could it be resolved?
Remove int from BinaryHeap b(int n); and b.insert( int ch); and you are good to go.
When you call a function you shouldn't specify the data type of the variables you call it with.
Try changing this
b.insert( int ch);
to this:
b.insert(ch);