A class that modifies the data of members of another class
I have two classes Maxsegtree
and Minsegtree
in my C ++ program.
The class Maxsegtree
has 2 private data members P
and Q
with dynamically allocated memory when instantiated.
The class Minsegtree
has similar 2 data items A
and B
.
When I call the member function of the class Minsegtree
, the item values Maxsegtree
A
change.
This is the ideal link to the program.
#include <iostream>
using namespace std;
class Maxsegtree
{
int* P;
int* Q;
public:
Maxsegtree(int N)
{
P = new int[N];
Q = new int[2 * N];
}
~Maxsegtree()
{
delete[] P;
delete[] Q;
}
int getP(int i)
{
return P[i];
}
void setP(int i, int x)
{
P[i] = x;
}
void build_tree(int node, int l, int r)
{
if (l == r)
Q[node] = l;
else
{
build_tree(node * 2, l, (l + r) / 2);
build_tree(node * 2 + 1, (l + r) / 2 + 1, r);
if (P[Q[2 * node]] > P[Q[2 * node + 1]])
Q[node] = Q[2 * node];
else
Q[node] = Q[2 * node + 1];
}
}
};
class Minsegtree
{
int* A;
int* B;
public:
Minsegtree(int N)
{
A = new int[N];
B = new int[2 * N];
}
~Minsegtree()
{
delete[] A;
delete[] B;
}
int getA(int i)
{
return A[i];
}
void setA(int i, int x)
{
A[i] = x;
}
void build_mintree(int node, int l, int r)
{
if (l == r)
B[node] = l;
else
{
build_mintree(node * 2, l, (l + r) / 2);
build_mintree(node * 2 + 1, (l + r) / 2 + 1, r);
if (A[B[2 * node]] <= A[B[2 * node + 1]])
B[node] = B[2 * node];
else
B[node] = B[2 * node + 1];
}
}
};
int main()
{
int n;
int x;
cin >> n;
Minsegtree mint(n);
Maxsegtree maxt(n);
for (int i = 0; i < n; i++)
{
cin >> x;
mint.setA(i, x);
maxt.setP(i, x);
}
cout << "Before function is called" << endl;
for (int i = 0; i < n; i++)
cout << maxt.getP(i) << " ";
cout << endl;
mint.build_mintree(1, 0, n - 1);
cout << "After function is called" << endl;
for (int i = 0; i < n; i++)
cout << maxt.getP(i) << " ";
cout << endl;
return 0;
}
Can someone please tell me what I am doing wrong?
source to share
Most likely you are accessing the array out of bounds.
Add checks with using std::vector
instead of raw pointer and using .at()
instead []
for access. Code:
B[node] = l;
eg,
B.at(node) = l;
This way, if you go outside the limits, an exception will be thrown std::out_of_range
.
Using vector
arrays instead of manually assigned ones will also take care of freeing and correctly implementing the constructor and copy assignment if you end up using them.
source to share