Constructor issue <Unable to read memory> - c++

I have to create a class Histogram and make operations on this class. The input can be one dimensional array or a two dimensional array. The problem appears when i convert the array into a matrix. This what i have tried so far. The error is <Unable to read memory>
histrogram.h
#ifndef HISTOGRAM_H
#define HISTOGRAM_H
#include<iostream>
class Histogram
{
private:
int** matrix;
int lines;
void SortMatrix();
public:
Histogram(){ }
Histogram(int elements[], int elementsNr);
Histogram(int** m, int l);
void Print();
};
#endif
historgram.cpp
#include"histogram.h"
using namespace std;
Histogram::Histogram(int** m, int l)
{
matrix=m;
lines=l;
SortMatrix();
}
Histogram::Histogram(int elements[], int elementsNr)
{
lines=0;
//initialize matrix : elementrNr lines and 2 columns
int** matrix=new int*[elementsNr];
for(int i=0;i<elementsNr;i++)
{
matrix[i]=new int[2];
matrix[i][0]=INT_MIN;
matrix[i][1]=INT_MIN;
}
//search each element from the array in the matrix
bool found=false;
for(int i=0;i<elementsNr;i++)
{
found=false;
for(int j=0;j<elementsNr;j++)
{
//the element was found in the matrix ( on the first column )
if(matrix[j][0] == elements[i])
{
matrix[j][1]++;
found=true;
break;
}
}
if(!found)
{
matrix[lines][0]=elements[i];
matrix[lines][1]=1;
lines++;
}
}
SortMatrix();
}
void Histogram::SortMatrix()
{
bool flag=true;
int temp;
for(int i=0;(i<lines) && flag;i++)
{
flag=false;
if(matrix[i+1][0]>matrix[i][0])
{
temp=matrix[i][0];
matrix[i][0]=matrix[i+1][0];
matrix[i+1][0]=temp;
flag=true;
}
}
}
void Histogram::Print()
{
for(int i=0;i<lines;i++)
{
cout<<matrix[i][0]<<" : " <<matrix[i][1]<<endl;
}
}
main.cpp
#include"histogram.h"
#include<iostream>
using namespace std;
int main()
{
int arr[]={6,7,3,1,3,2,4,4,7,5,1,1,5,6,6,4,5};
Histogram h(arr,17);
h.Print();
}

Here
int** matrix=new int*[elementsNr];
replace with
matrix=new int*[elementsNr];
becausematrix is already a member variable. You are creating a new temporary variable double pointer named matrix and allocating memory to it rather than your member variable matrix

A couple of people have already given you advice about how to fix some of the problems with this code. I'll give slightly different advice that may initially seem a bit brutal by comparison, but I'll try to demonstrate how it's honestly useful rather than nasty.
I would throw out your existing code with the possible exception of what you have in main, and start over, using an std::map. What you're doing right now is basically trying to re-create the capabilities that std::map already provides (and even when your code is fixed, it's not doing the job as well as std::map does right out of the box).
Using map, your whole program comes out to something like this:
std::ostream &operator<<(std::ostream &os, std::pair<int, int> const &d) {
return os << d.first << " : " << d.second;
}
int main() {
std::map<int, int> h;
for (int i=0; i<17; i++)
++h[arr[i]];
std::copy(h.begin(), h.end(),
std::ostream_iterator<std::pair<int, int> >(std::cout, "\n"));
return 0;
}
If you want to maintain virtually the same interface as your histogram class provided, it's pretty easy to do that -- the for loop goes into the constructor, the copy into print (and SortMatrix disappears, because a map is always sorted).
By doing this, you change from an O(N2) algorithm to an O(N log N) algorithm. The bugs others have pointed out disappear completely, because the code that contained them is no longer needed. The only real disadvantage I can see is that the result will probably use a bit more memory -- it uses a balanced tree with individually allocated nodes, which is likely to introduce a fair amount of overhead for nodes that only contain 2 ints (and a bit for balancing). I can't quite imagine worrying about this though -- long before you have enough nodes for the memory usage to become significant, you have way too many to present to even consider presenting to the user.

#mathematician1975 already provided an answer for the main problem. There's another bug in SortMatrix(): you only swap the elements of the first column, therefore after sorting, the counts (in the second column) will not be correct anymore. You'll have to insert
temp=matrix[i][1];
matrix[i][1]=matrix[i+1][1];
matrix[i+1][1]=temp;
to get it working.

Related

Balance ordering parenthesis via Dynamic programing

Hi from the very famous book Code to Crack i come across a question :
Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.
Example:
input: 3 (e.g., 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))
#include <iostream>
#include <string>
using namespace std;
void _paren(int l,int r,string s,int count);
void paren(int n)
{
string s="";
_paren(n,n,s,n);
}
void _paren(int l,int r,string s,int count){
if(l<0 || r<0)
return;
if(l==0 && r==0)
cout<<s<<endl;
else{
if(l>0)
{
_paren(l-1,r,s+"(",count+1);
}
if(r>l)
_paren(l,r-1,s+")",count+1);
}
}
int main(){
int n;
cin>>n;
paren(n);
return 0;
}
This is a recursive approach I tried for it . I am pretty sure that we can solve this through dynamic programming as well , as we are already using a lot of value again and again , but I have no idea how to implement this through Dynamic programming I tried tabular bottom up approach but couldnt work out. Please help me out just the basic idea on how to work with this
DP does not really help you. The recursive algorithm is time and space optimal!
In fact, there is a reason not to use DP: the memory requirements! This will be huge.
A better algorithm is to have one character array that you pass in, have the recursive method modify parts of it and print that when needed. I believe that solution is given in the book you mention.
DP can reduce count of traversed states by choosing the optimal solution every call. It also help you to reuse calculated values. There is no calculations, every valid state must be visited, and non-valid states can be avoided by if( ).
I suggest you to implement some another recursion (at least without copying new string object after call, just declare global char array and send it to output when you need).
My idea of recursion is
char arr[maxN]; int n; // n is string length, must be even though
void func(int pos, int count) { // position in string, count of opened '('
if( pos == n ) {
for(int i = 0; i < n; i++)
cout << char(arr[i]);
cout << "\n";
return;
}
if( n-pos-1 > count ) {
arr[pos] = '('; func(pos+1,count+1);
}
if( count > 0 ) {
arr[pos] = ')'; func(pos+1,count-1);
}
}
I didn't checked it, but the idea is clear I think.

Run time error for dynamic memory allocation in C++

I am a newbie for OOP concepts and while trying to solve Project Euler Problem 7, to find 10001th prime number, I tried to do it using a class but encountered 2 major errors.
instantiating the class prime_n
initializing its argument
I have posted the code here for reference:
#include<iostream>
#include<cstdio>
using namespace std;
class prime_n
{
int j,k;
int n;
int *store;
public:
prime_n(int num)
{
n=num;
store[n];
}
static int isPrime(int j)
{
for(int i=2;i*i<=j;i++)
{
if(j%i==0) return 0;
}
return 1;
}
void find_n()
{
for(int i=0;i<n;i++)
{
store[i]=0;
}
store[0]=2;
j=3;
k=1;
while(store[n-1]==0)
{
if(isPrime(j)) store[k++]=j;
j+=2;
}
}
int get_num()
{
int value=store[n-1];
return value;
}
};
int main()
{
int num, req_num;
printf("Enter the position at which prime number is to be found ");
scanf("%d",&num);
printf("\nnumber = %d",num);
prime_n p = new prime_n(num);
req_num = p.get_num();
printf("The required prime number is %d\n",req_num);
return 0;
}
It would be a great help if someone could help me figure out where I am actually going wrong. Thanks a lot in advance!
Use
prime_n p(num);
or (not recommended in this particular case)
prime_n * p = new prime_n(num);
// some other code
req_num = p->get_num(); // note the -> operator replacing . in case of pointers
delete p;
The first case declares p on stack and it is automatically deallocated when the program leaves the scope (main function in this case)
The second one allocates space on heap and p is the pointer to it. You have to deallocate the memory manually.
As for your second question, the C++ way would be
#include <iostream>
...
int num;
std::cout << "Enter the position at which prime number is to be found "
std::cin >> num;
std::cout << std::endl << "Number = " << num << std::endl;
You provide a constructor:
prime_n(int num)
{
n=num;
store[n];
}
I think you are under the impression that store[n] creates an array with n elements, but that is not so; it attempts to access the (n+1)th element of an an array. Since store does not point anywhere (we are in the constructor, after all), the program crashes.
You probably want to write store = new int[num] instead.
And then I cannot see any call to find_n() originating from get_num() which is called in main(), so that your program would for now just return a random value.

A C++ implementation of topological ordering

This morning I was doing my C++ class assignment, an implementation of topological ordering. There's no error while compiling, but simply can't run. Since I'm not quite familiar with pointers or STL, nor the VS debugger...I just can't figure out where went wrong. It would help me a lot if someone can point out my errors. Tons of thanks!
Here's my code:
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
typedef struct Vertex{
int index;
int indegree; // indegree of vertex v is the total num of edges like(u,v)
vector<Vertex>adjacent;
int topoNum; // topological order of this vertex.
}Vertex;
typedef struct Edge{
Vertex start;
Vertex in;
}Edge;
Vertex*InDegrees(int numVertex,int numEdge,Edge*edges) // calculate indegrees of all vertices.
{
Vertex*vertices=new Vertex[numVertex];
for(int i=0;i<numVertex;i++){ vertices[i].index=i; vertices[i].indegree=0;}
for(int i=0;i<numEdge;i++)
{
int j=edges[i].in.index;
vertices[j].indegree++;
vertices[j].adjacent.push_back(edges[i].start);
}
return vertices;
}
int*topoSort(int numVertex,int numEdge,Edge*edges)
{
edges=new Edge[numEdge];
Vertex*Vertices=new Vertex[numVertex];
Vertices=InDegrees(numVertex,numEdge,edges);
queue<Vertex>q;
for(int i=0;i<numVertex;i++)
{
if(Vertices[i].indegree==0)
q.push(Vertices[i]);
}
int count=0;
while(!q.empty()) // Ordering completed when queue is empty.
{
Vertex v=q.front(); // get the vertex whose indegree==0
q.pop();
v.topoNum=++count;
vector<Vertex>::iterator iter;
for(iter=v.adjacent.begin();iter!=v.adjacent.end();iter++)
{
Vertex w=*iter;
if(--w.indegree==0)
q.push(w);
}
}
int*topoOrder=new int[numVertex];
for(int i=0;i<numVertex;i++)
{
int j=Vertices[i].topoNum;
topoOrder[j]=-1; // initial value, in case cycle existed.
topoOrder[j]=Vertices[i].index;
}
delete[]Vertices;
delete[]edges;
return topoOrder;
}
int main()
{
int numVertex,numEdge;
cin>>numVertex>>numEdge;
Edge*Edges=new Edge[numEdge];
int indexStart,indexIn;
for(int i=0;i<numEdge;i++)
{
cin>>indexStart>>indexIn;
Edges[i].in.index=--indexIn;
Edges[i].start.index=--indexStart;
}
int*topoOrder=new int[numVertex];
topoOrder=topoSort(numVertex,numEdge,Edges);
for(int i=0;i<numVertex-1;i++)
{
if(topoOrder[i]==-1)
{
cout<<"Cycle exists, not a DAG!";
return 0;
}
cout<<topoOrder[i]<<",";
}
cout<<topoOrder[numVertex-1]<<endl;
delete[]Edges;
return 0;
}
An obvious starting point for your problems is the allocation for Edges: the allocation uses the uninitialized value numEdge which is likely to be zero. That is, you'll get a pointer to no elements. You probably want to allocate Edges only after having read numEdge. I didn't really had a look at what happens in the actual algorithm.
I also strongly recommend that you verify that the input operations were successful:
if (std::cin >> numVertex >> numEdge) {
use_successfully_read(numVertex, numEdge);
}
If inputs fail the variable remain unchanged and the values will also lead to interesting behavior.

Variable length arrays depending on length of file C++

I'm encountering a problem trying to generalize my algorithm for any-size problems.
The code is working for the test problem I used, but I had to insert manually the lenght of some arrays. Next, I've tried reading the lenght of input files in two variables, but then I'm not able to use them in all of my code, but just in some pieces. I think it's quite a stupid thing, but I'm really new to C++ and I'd like to get help.
Here's the piece of code:
#include <fstream>
#include <iostream>
#include <time.h>
using namespace std;
struct node{
int last_prod;
int last_slot;
float ZL;
float ZU;
float g;
bool fathomed;
node *next;
node *padre;
node *primofiglio;
};
clock_t start, end;
double cpu_time_used;
int l=0;
int cont_slot=0;
int cont_prod=0;
float temp_cont;
float distanze[360]; // dichiarazione variabili
int slot[111];
int slot_cum[111];
float COIp[111];
int domanda[111];
float Zb=9999999999999999;
float LowerBound(struct node *n);
float UpperBound(struct node *n);
float h(struct node *l,struct node *n);
void creasottolivello(struct node *n);
void fathRule2(struct node *n);
void fathRule3(struct node *n);
void stampaRisultati(struct node *n, ofstream &f);
int unFathomedNodes(struct node *n);
void append(struct node* temp, struct node* n);
void ricercaOttimo(struct node *n, ofstream &f);
void calcoloBounds(struct node *n);
int main(){
start = clock();
ifstream contdist_file ( "/Users/MarcoBi/Desktop/TESI di LAUREA/Xcode/dati/distanze.txt" ); // conteggio dati input
if ( !contdist_file.is_open() ) { //conta righe file slot
}
else {
for(int i=0; !contdist_file.eof(); i++){
contdist_file >> temp_cont;
cont_slot++;
}
}
ifstream contslot_file ( "/Users/MarcoBi/Desktop/TESI di LAUREA/Xcode/dati/slot.txt" );
if ( !contslot_file.is_open() ) { //conta righe file prodotti
}
else {
for(int i=0; !contslot_file.eof(); i++){
contslot_file >> temp_cont;
cont_prod++;
}
}
....
As you can see, in the main() I count the lenght of input files into cont_prod and cont_slot variables, but then I can't use them in variable declaration. The variable lenght arrays I need have to be global variables 'cuz I need them also in other functions. And also cont_prod and cont_slot need to be global, as I need them in local variable declarations in some functions.
Here is one of the functions I need to use them in:
float LowerBound(struct node *n){ //funzione LowerBound
int S[111];
int Sp=0;
float d[111];
float dmin[111];
float D;
float LB;
for(int i=n->last_prod;i<111;i++){
Sp=Sp+slot[i];
}
for(int i=0;i<111;i++){ //Calcolo S_pigreco
S[i]=0;
}
if(n->last_prod==0){ //condizione necessaria per nodo radice
S[0]=slot[0];
for(int i=n->last_prod +2;i<111;i++){
for(int j=n->last_prod +1;j<=i;j++){
S[j]=S[j-1]+slot[j];
}
}
}
else{
for(int i=n->last_prod +1;i<111;i++){
for(int j=n->last_prod;j<=i;j++){
S[j]=S[j-1]+slot[j];
}
}
}
S[110]=S[109] + slot[110];
//calcolo somma distanze da slot j+1 a q
for(int i=0;i<111;i++){
d[i]=0;
}
for(int j=n->last_prod;j<111;j++){
for(int i=n->last_slot; i < n->last_slot +S[j]; i++){
d[j]=d[j]+distanze[i];
}
}
//calcolo dmin_pigreco
for(int i=n->last_prod; i<111; i++){
dmin[i]= d[i]/S[i];
}
D=0;
for(int i=n->last_prod; i<111; i++){
D=D+dmin[i]*domanda[i];
}
LB=n->g+2*D;
return LB;
}
111 is cont_prod and 360 is cont_slot.
I'm programming on a Mac in Xcode and it says that variable lenght arrays cannot be declared at file scope, which I think it means as global variables.
How can I manage that?
Just focusing on your actual question here: in C++, you create variable length-arrays using std::vector, like this:
std::vector<char> myCharArray( n * 1000 );
You can then use the expression
&myCharArray[0]
to use the vector object in all cases where you'd normally pass a raw C array.
Perhaps declare pointers at file scope and allocate memory dynamically as and when you know the values...
Declare
int *slot
and allocate memory as
slot = new int[cont_slot];
and after using dont forget to "delete [] slot" it .. :)
Disclaimer: I didn't read the whole question, but it seems to me like you need either a dynamically allocated array:
float* distanze = new float[length];
or, better yet, a std::vector:
std::vector<float> distanze; // <-- this is the proper C++ way
You can insert values in the vector via distanze.push_back(float) and iterate through it just like it was an array, with operator [].
For starters, you should learn to format your code.
Secondly, in C++, an array is normally declared with something like:
std::vector<float> anArray;
The declaraion using a [] is a left-over from C, and is only used in
very special cases (once you've fully mastered std::vector). And a
vector will extend itself automatically if you use push_back to insert
values. And an std::vector carries its size around with it, so you
can iterator using:
for ( int i = 0; i != v.size(); ++ i ) {
// use `v[i]` here...
}
You can also iterate using iterators, which is more idiomatic in general
(but perhaps not in the case where you are doing numerical work).
Finally, std::istream::eof() is really only useful once input has
failed (to know whether the failure is due to end of file, or something
else). The usual idiom to read would be something like:
float value;
while ( contdist_file >> value ) {
distanze.push_back( value );
}
(I'm supposing that this is what you actually want in the first loop.
In the code you've posted, you just read into a temporary variable,
overwriting each time, but not otherwise doing anything with the value
you read.)
Finally, unless your vectors may be very large, it's usual to use
double in C++, rather than float. (But this depends on the
total amount of data you need to handle, as well as the precision you
need.) Note too that a loop with:
Sp += slot[i];
will likely give very poor results if the size of slot is large,
unless you're lucky with the values in slot. If the values are in the
range of 0.5...1, for example, after a couple of thousand values, with
float, you only have about 3 or 4 decimal digits of precision, and if
the first value happens to be 10000000, any following values less than 1
are treated as zero. Typically, you need special algorithms to sum up
floating point sequences. (Using double will improve things, but not
eliminate the problem.)

Delete a record in an array

int i;
int Input;
cin >> Input;
for(i = 0; i < Size ; i ++ )
if (List[i].PersonID == Input) {
}
I am trying to make a function that deletes a record from the array based on the id input provided. I am not sure what to do beyond this here. Will I also need to shift the values in the array after a record is removed?
I can't tell what type your List is.
But you should go for something like this:
List.RemoveAt(i--);
List.DeleteAt(i--);
i-- will decrement i AFTER the function has been called.
You should not need to shift any values in the array if you are using the standard containers.
If you are responsible for the array, then you do need to shift your values.
** EDIT
Here is a link to an introduction to the standard containers. If you are managing your own dynamic array you should consider using these instead.
Here I'm assuming List is a primitive array of ints.
#include<algorithm> // where std::remove() resides
#include<iterator> // where std::distance() resides (not strictly necessary)
struct BadPerson {
BadPerson(int Bad) : Bad_(Bad) { }
bool operator()(const Element& Elem) const {
return Elem.PersonID == Bad_;
}
};
// ...
int *NewEnd = std::remove_if(List, List + ListLength, BadPerson);
// the list now has a new end, because elements were "removed".
// but they weren't really removed; the array still has the same fixed size.
int ListLength = std::distance(List, NewEnd);
I think the best way to remove elements from an array/vector is to use a copy approach with something like:
int write_ptr = 0;
for (int read_ptr=0; read_ptr < n; read_ptr++)
{
if (... keep element array[write_ptr] ? ...)
{
if (read_ptr != write_ptr)
array[write_ptr] = array[read_ptr];
write_ptr++;
}
}
// The new size of the array is write_ptr
This will allow to remove even multiple elements with just one pass.
The standard library includes this approach as std::remove_if, however until C++0X arrives it's annoying to use because of limitations of the language (the code needed to be able to specify the test becomes easily quite ugly).
int i;
int Input;
cin >> Input;
for(i = 0; i < Size ; i ++ )
{
if (List[i].PersonID == Input)
{
for(int j=i;j<size-1;j++)
{
List[j]=List[j+1];
}
}
}