I'm doing QuickSort but i'm getting bad_alloc() error.Sometimes code run perfectly but some time i'm getting error.The program run perfectly and do sort right but only when it's run but s out of 4 times it's give me bad _alloc error.
so what's the problem???????
#include <iostream>
using namespace std;
void quicksort(int *a,int,int);
int main()
{
int i,j,*a;
a = new int[j];
cout<<"Enter the total element:";
cin>>j;
for(i=0;i<j;i++){
cout<<"Enter element:";cin>>a[i];
}
quicksort(a,0,j-1);
cout<<"After sorting."<<endl;
for(i=0;i<j;i++){
cout<<a[i]<<endl;
}
return 0;
}
void quicksort(int *a,int u,int d){
int key = a[u];
int upper = u;
int lower = d;
while(key>a[u] && u<lower){
u++;
}
while(key<a[d] && d>upper){
d--;
}
if(u<d){
swap(a[u],a[d]);
quicksort(a,upper,lower);
}
if(u>=d){
swap(key,a[d]);
if(upper!=d)
{
quicksort(a,upper,d-1);
}
if(d!=lower)
{
quicksort(a,d+1,lower);
}
}
}
Move the statement
a = new int[j];
after
cin>>j;
You are allocating with "junk" as j takes the value whatever in the local stack memory location have!
Related
I was writing this task https://codeforces.com/contest/459/problem/D on codeforces and my solution uses trees, but after running update function every element goes back to 0.
#include<bits/stdc++.h>
using namespace std;
int n,k,a[1000009],ans1[1000009],ans2[1000009],fans,w;
map<int,int> pref;
struct Node{
Node *L,*R;
int Sum;
Node()
{
Sum=0;
L=NULL;
R=NULL;
}
}*root = new Node();
void update(Node *it,int l,int r,int q)
{
if(it==NULL) it = new Node();
if(q<l || q>r) return;
it->Sum ++;
cout<<l<<" "<<r<<" "<<q<<" "<<it->Sum<<endl;
if(l==r) return;
update(it->L,l,(l+r)/2,q);
update(it->R,(l+r)/2+1,r,q);
}
void findans(Node *it,int l,int r,int L,int R)
{
if(it==NULL)
{
it = new Node();
cout<<"1 ";
}
cout<<l<<" "<<r<<" "<<L<<" "<<R<<" "<<it->Sum<<endl;
if(l>=L && r<=R) w+=it->Sum;
if(l!=r) if(l<=R && r>=L)
{
findans(it->L,l,(l+r)/2,L,R);
findans(it->R,(l+r)/2+1,r,L,R);
}
}
int main()
{
cin>>n;
for(k=1;k<=n;k++)
{
cin>>a[k];
pref[a[k]]++;
ans1[k]=pref[a[k]];
}
pref.clear();
for(k=n;k>=1;k--)
{
pref[a[k]]++;
ans2[k]=pref[a[k]];
}
for(k=n;k>=1;k--)
{
w=0;
findans(root,1,n,1,ans1[k]-1);
fans+=w;
update(root,1,n,ans2[k]);
cout<<endl;
}
cout<<fans;
}
this is the code(I have extra couts so I could find out where was the problem). also root gets updated normally but every other nodes -> sum goes back to 0 ( sorry for my bad english )
if(it==NULL) it = new Node();
it itself is a local variable, so any changes to it will only be scoped to the function. In other words, calling findans(x, ...) will leave x in the same state it was prior to calling the function.
To fix this, change findans() to accept a reference to a pointer:
void update(Node *&it,int l,int r,int q)
{
...
}
Here is my code for quick sort. I am a beginner kindly please help.
#include<iostream>
using namespace std;
class quick
{
private:
int n,left,right,i,j;
float a[55];
public:
void getdata();
void sort(float[],int,int);
void putdata();
};
void quick::getdata()
{
cout<<"Enter how many elements you want to enter:";
cin>>n;
for(int k=0;k<n;k++)
{
cout<<"Enter percentage of students:"<<k+1<<":";
cin>>a[k];
}
left=0;
right=n-1;
}
void quick::putdata()
{
for(int k=0;k<5;k++)
{
cout<<"\nSorted marks are:"<<a[k]<<endl;
}
}
void quick::sort(float a[],int left,int right)
{
if(left<right)
{
int i=left;
int j=right+1;
float pivot=a[left];
do{
do{
i++;
}while((a[i]<pivot)&& left<right);
do{
j--;
}while(a[j]>pivot);
if(i<j)
swap(a[i],a[j]);
}while(i<j);
a[left]=a[j];
a[j]=pivot;
sort(a,left,j-1);
sort(a,j+1,right);
}
}
int main()
{
quick obj;
obj.getdata();
obj.sort(a[],left,right);
obj.putdata();
return (0);
}
It is giving me error in int main() function:
a is not declared in this scope.
expected primary expression before ']'.
As the answer is given by #Shubham Khatri. Here is the corrected code.
#include<iostream>
using namespace std;
class quick
{
public: int n,left,right,i,j;
float a[55];
public:
void getdata();
void sort(float[],int,int);
void putdata();
};
void quick::getdata()
{
cout<<"Enter how many elements you want to enter:";
cin>>n;
for(int k=0;k<n;k++)
{
cout<<"Enter percentage of students:"<<k+1<<":";
cin>>a[k];
}
left=0;
right=n-1;
}
void quick::putdata()
{
for(int k=0;k<n;k++)
{
cout<<"\nSorted marks are:"<<a[k]<<endl;
}
}
void quick::sort(float a[],int left,int right)
{
if(left<right)
{
int i=left;
int j=right+1;
float pivot=a[left];
do{
do{
i++;
}while((a[i]<pivot)&& left<right);
do{
j--;
}while(a[j]>pivot);
if(i<j)
swap(a[i],a[j]);
}
while(i<j);
a[left]=a[j];
a[j]=pivot;
sort(a,left,j-1);
sort(a,j+1,right);
}
}
int main()
{
quick obj;
obj.getdata();
obj.sort(obj.a,obj.left,obj.right);
obj.putdata();
return (0);
}
As it mentions you have not declared a as a variable inside the int main(). Rather it is an object of quick. In a function you don't pass array like a[] rather as a only .since a, left, right are a private variable of a class you can't access it from the object directly. Declare it as public and use it as obj.a, obj.left, obj.right inside sort function.
Complete code:
#include<iostream>
using namespace std;
class quick
{
public:
int n,left,right,i,j;
float a[55];
void getdata();
void sort(float[],int,int);
void putdata();
};
void quick::getdata()
{
cout<<"Enter how many elements you want to enter:";
cin>>n;
for(int k=0;k<n;k++)
{
cout<<"Enter percentage of students:"<<k+1<<":";
cin>>a[k];
}
left=0;
right=n-1;
}
void quick::putdata()
{
for(int k=0;k<5;k++)
{
cout<<"\nSorted marks are:"<<a[k]<<endl;
}
}
void quick::sort(float a[],int left,int right)
{
if(left<right)
{
int i=left;
int j=right+1;
float pivot=a[left];
do{
do{
i++;
}while((a[i]<pivot)&& left<right);
do{
j--;
}while(a[j]>pivot);
if(i<j)
swap(a[i],a[j]);
}while(i<j);
a[left]=a[j];
a[j]=pivot;
sort(a,left,j-1);
sort(a,j+1,right);
}
}
int main()
{
quick obj;
obj.getdata();
obj.sort(obj.a,obj.left,obj.right);
obj.putdata();
return (0);
}
#include<iostream>
using namespace std;
class ulam
{
int num;
double prod;
int cot;
public:
ulam(){cot=0;}
ulam(int x)
{
num=x;
}
void process()
{
for(int i=0;num==1;i++)
{
cout<<num<<endl;
if((num%2) == 0)
{
prod=num/2;
}
else
{
prod=(3*num)+1;
}
num=prod;
cot++;
}
}
void display()
{
cout<<"the number of steps required is: "<<cot;
}
};
int main()
{
int n;
cout<<"enter the number"<<endl;
cin>>n;
ulam obj(n);
obj.process();
obj.display();
}
when i write this code the cot value comes as a garbage value i think. i cant figure out where i went wrong. i used class because i feel it is more discriptive . but the main aim behind this program is to find the number of steps it is required for a number to reach one and to print the whole sequence of numbers. for thos who dont know about the collatz conjecture https://en.wikipedia.org/wiki/Collatz_conjecture
Your condition of the for loop inside process function is wrong. it should be num!=1. You need to initialize cot too. You don't need prod actually.
#include<iostream>
using namespace std;
class ulam
{
int num;
int cot;
public:
ulam()
{
cot=0;
}
ulam(int x)
{
cot=0;
num=x;
}
void process()
{
for(int i=0;num!=1;i++)
{
cout<<num<<endl;
if((num%2) == 0)
{
num=num/2;
}
else
{
num=(3*num)+1;
}
cot++;
}
}
void display()
{
cout<<"the number of steps required is: "<<cot;
}
};
int main()
{
int n;
cout<<"enter the number"<<endl;
cin>>n;
ulam obj(n);
obj.process();
obj.display();
return 0;
}
First Problem
In the constructor where you initialize when an integer is passed, you ALSO have to initialize cot like this:
ulam(int x)
{
cot = 0;
num = x;
}
Better yet, since cot is always going to be 0 at construction, just set cot to 0 as a private variable like this:
class ulam
{
int num;
double prod;
int cot = 0;
public:
//....
};
This means that you could still have a default constructor that will do nothing, and the one that takes an integer won't require cot to be set to 0.
Second Problem
Your second problem is that the loop condition is wrong. It should be num != 1, not num == 1. num == 1 would be the loop would never run unless 1 was passed in cin.
Header File (IntegerSet.h)
#include<iostream>
#include<string>
using namespace std;
class IntegerSet{
public:
unsigned int set[15];
unsigned int empty_set[15];
IntegerSet();
IntegerSet(int[],int);
IntegerSet unionOfsets(IntegerSet);
IntegerSet intersectionOfSets(IntegerSet);
void insertElement(int);
void deleteElement(int);
void printSet();
bool isEqualTo(IntegerSet);
void emptySet();//Set all elements of set to 0
void inputSet();//Reads values from the user into set
bool validEntry(int);//Determines a valid entry to the set
};
Implementation File (IntegerSet.cpp)
//Class implementation file
#include "IntegerSet.h"
using namespace std;
IntegerSet::IntegerSet(){
for(int i=0;i<100;i++){
empty_set[i]=0;
}
}
IntegerSet::IntegerSet(int arr[],int size){
int min;//Use to hold the value for the sorting algorithm
int counter;//Used to count how many values need to be removed from the new array
for(int i=0;i<size-1;i++){//Nested for loop used to sort the array in ascending order
min=arr[i];
if(arr[i]<0||arr[i]>100){//If statement used to count how many numbers are <0 or >100
counter++;
}
for(int k=i+1;k<size;k++){
if(arr[k]<min){
arr[i]=arr[k];
arr[k]=min;
min=arr[i];
}
}
}
int *newSet=new int[size-counter];
for(int j=0;j<size;j++){
if(arr[j]>100||arr[j]<0){
//Do nothing
}else{
newSet[j]=arr[j];
}
}
delete newSet;
}
bool IntegerSet::validEntry(int a){
if(a<0||a>100){
return false;
}
return true;
}
void IntegerSet::inputSet(){
int a;
for(int i=0;i<100;i++){
cout<<"Enter an element(-1 to end)";
cin>>a;
if(a==-1){
cout<<"Entry complete";
return;
}
this->set[i]=a;
}
}
void IntegerSet::emptySet(){
for(unsigned int i=0;i<sizeof(this->set);i++){
this->set[i]=0;
}
}
IntegerSet IntegerSet::unionOfsets(IntegerSet a){
unsigned int *Union=new unsigned int[sizeof(this->set)+sizeof(a.set)];
for(unsigned int i=0;i<sizeof(this->set);i++){
*(Union+i)=this->set[i];
for(unsigned int h=0;h<sizeof(this->set);h++){
*(Union+(h+i))=a.set[h];
}
}
for(unsigned int j=0;j<sizeof(*Union);j++){
for(unsigned int z=j+1;z<sizeof(*Union);z++){
if(*(Union+j)==*(Union+z)){
*(Union+z)=0;
}
}
}
unsigned int newUnion[sizeof(*Union)];
for(unsigned int y=0;y<sizeof(*Union);y++){
if(*(Union+y)!=0&&y<sizeof(newUnion)){
newUnion[y]=*(Union+y);
}
}
IntegerSet c;
for(unsigned int w=0;w<sizeof(*Union);w++){
c.set[w]=newUnion[w];
}
delete Union;
return c;
}
IntegerSet IntegerSet::intersectionOfSets(IntegerSet a){
unsigned int *Intersect=new unsigned int[sizeof(this->set)+sizeof(a.set)];
int counter=0;
for(unsigned int i=0;i<sizeof(this->set);i++){
for(unsigned int j=0;j<sizeof(a.set);j++){
if(this->set[i]==a.set[j]){
*(Intersect+counter)=a.set[j];
counter++;
}
}
}
IntegerSet c;
for(unsigned int w=0;w<sizeof(*Intersect);w++){
c.set[w]=*(Intersect+w);
}
delete Intersect;
return c;
}
void IntegerSet::printSet(){
unsigned int min;
for(unsigned int i=0;i<sizeof(this->set)-1;i++){
min=this->set[i];
for(unsigned int k=i+1;k<sizeof(this->set);k++){
{
if(this->set[k]<min){
this->set[i]=this->set[k];
this->set[k]=min;
min=this->set[i];
}
}
}
cout<<"{";
for(unsigned int h=0;h<3;h++){
if(h==sizeof(this->set)-1){
cout<<this->set[h]<<"}";
}else{
cout<<this->set[h]<<",";
}
}
}
bool IntegerSet::isEqualTo(IntegerSet a){
unsigned int counter=0;
if(sizeof(a.set)==sizeof(this->set)){
for(unsigned int i=0;i<sizeof(this->set);i++){
for(unsigned int f=0;f<sizeof(a.set);f++){
if(this->set[i]==a.set[f]){
counter++;
}
}
}
}else{
return false;
}
if(counter==sizeof(this->set)){
return true;
}
return false;//Used to make sure this method always has something to return
}
void IntegerSet::insertElement(int a){
unsigned A=(unsigned)a;
if(!this->validEntry(a)){
cout<<"Invalid Insertion Attempt!";
}
unsigned int Inserted[sizeof(this->set)+1];
Inserted[sizeof(this->set)]=A;
for(unsigned int w=0;w<sizeof(Inserted);w++){
this->set[w]=Inserted[w];
}
}
void IntegerSet::deleteElement(int a){
unsigned A=(unsigned) a;
unsigned int *Delete=new unsigned int[sizeof(this->set)-1];int test=0;
if(!this->validEntry(a)){
cout<<"No value of: "<<a<<" exists in the set";
}
for(unsigned int z=0;z<sizeof(this->set);z++){
if(this->set[z]==A){
test++;
}
}
if(test==0){
cout<<"No value of: "<<a<<" exists in the set";
}
for(unsigned int i=0;i<sizeof(this->set)-1;i++){
*(Delete+i)=this->set[i];
}
for(unsigned int w=0;w<sizeof(*Delete);w++){
this->set[w]=*(Delete+w);
}
delete Delete;
}
And then there is my tester file, which is what allowed me to find the error
(IntSet.cpp)
//Driver program for class IntegerSet
#include <iostream>
using namespace std;
#include "IntegerSet.h"
int main(){
IntegerSet a,b,c,d;
cout<<"Enter set A:\n";
a.inputSet();
cout<<"\nEnter set B:\n";
b.inputSet();
c=a.unionOfsets(b);
d=a.intersectionOfSets(b);
cout<<"\nUnion of A nd B is:\n";
c.printSet();
cout<<"Intersection of A nd B is:\n";
d.printSet();
//Test if set A is equal to set B
if(a.isEqualTo(b)){
cout<<"Set A is equal to set B\n";
}else{
cout<<"Set A is not equal to set B\n";
}
//test insertion
cout<<"\nInserting 77 into set A...\n";
a.insertElement(77);
cout<<"Set A is now:\n";
a.printSet();
const int arraySize=10;
int intArray[arraySize]={25,67,2,9,99,105,45,-5,100,1};
//Use construct that receive an array of ints
//and the size of that array to create a set object
IntegerSet e(intArray,arraySize);
cout<<"\nSet e is:\n";
e.printSet();
cout<<endl;
}
Personally I feel like what caused this error was some sort of memory leak, although the glib c error isn't exactly telling me where it would be coming from like the compiler does. Also this error occurs right after the function b.inputSet() exits.
What the error says (it alternates between two messages I've noticed):
***glibc detected*** ./a.out: free(): invalid next size (normal):
***glibc detected*** ./a.out: double free or corruption (!prev):
You're doing lots of bad here.
Here's your definition of empty_set.
unsigned int empty_set[15];
And your default constructor accesses outside these bounds.
IntegerSet::IntegerSet(){
for(int i=0;i<100;i++){
empty_set[i]=0;
}
}
Your other constructor doesn't actually change anything inside the class.
Also this code
IntegerSet IntegerSet::unionOfsets(IntegerSet a){
unsigned int *Union=new unsigned int[sizeof(this->set)+sizeof(a.set)];
looks remarkably suspicious as sizeof(set) is not the number of elements in set, but the array length in bytes (15*sizeof(float)) - but if you switch to a variable length array it wont even be that... You'll need to track the set length separately. Or use a std::vector<int>, or better yet - why reinvent the wheel and use std::set<int>?
I know this error is because i have declared stu inside the for loop scope but its the necessity of the program.I want to declare an array for each test case (test case should all be input at once).Suggest me a way to achieve this.Is dynamic memory an alternative.
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int t;
cin>>t;
int n[t],g[t];
int m =0;
for(int w=0;w<t;t++)
{
cin>>n[w]>>g[w];
int stu[n[w]];
for(int i=0;i<n[w];i++)
{
cin>>stu[i];
}
}
while(m<t)
{
int a,b;
int e;
e = (n[m]*(n[m]-1))/2;
int diff[e];
if (g[m]=1)
{
cout<<0<<endl;
return 0;
}
b=*(min_element(stu,stu+n[m]-1));
a=*(max_element(stu,stu+n[m]-1));
if (g[m]=n[m])
{
cout<<a-b<<endl;
return 0;
}
int z = 0;
for(int j=0;j<(n[m]-1);j++)
{
for(int k=(j+1);k<n[m];k++)
{
diff[z]=abs(stu[j]-stu[k]);
++z;
}
}
cout<<*(min_element(diff,diff+e-1))<<endl;
++m;
}
cin.ignore();
cin.get();
return 0;
}
You are declaring stu inside of a for loop, so it is limited to the scope of the loop. You then try to use it outside of the loop, where it is undeclared.
for(int w=0;w<t;t++)
{
...
int stu[n[w]]; // Beware: stu is a VLA. Non-standard C++.
// OK to use stu here
...
}
// stu doesn't exist here
Also note that standard C++ does not support variable length arrays (VLAs), which is what you are attempting to use in the declaration of stu, as well as here:
int t;
cin>>t;
int n[t],g[t];
You can replace these arrays by std::vector<int>:
#include <iostream>
#include <vector>
int main()
{
int t=0;
cin>>t;
std::vector<int> n(t);
std::vector<int> g(t);
std::vector<int> stu ...;
}
The line
int stu[n[w]];
is inside a block and outside that block it won't be seen. You should move it out of the block, but doing so of course you can't use n[w], being w the looping var. You coudl put a limit to the max value n[w] can have, e.g.
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXV = 100;
int main()
{
int t;
cin>>t;
int n[t],g[t]; // <- supported by some compiler, but not std
int m =0;
int stu[MAXV];
for(int w=0;w<t;t++) {
cin>>n[w]>>g[w];
for(int i=0;i<n[w] && i < MAXV;i++) {
cin>>stu[i];
}
}
while(m<t) {
int a,b;
int e;
e = (n[m]*(n[m]-1))/2;
int diff[e];
if (g[m]==1) {
cout<<0<<endl;
return 0;
}
b=*(min_element(stu,stu+n[m]-1));
a=*(max_element(stu,stu+n[m]-1));
if (g[m]==n[m]) {
cout<<a-b<<endl;
return 0;
}
int z = 0;
for(int j=0;j<(n[m]-1);j++) {
for(int k=(j+1);k<n[m];k++) {
diff[z]=abs(stu[j]-stu[k]);
++z;
}
}
cout<<*(min_element(diff,diff+e-1))<<endl;
++m;
}
cin.ignore();
cin.get();
return 0;
}
(I've fixed a couple of assignment in conditional when I suppose you meant == and not =, but I've not tested if the code does what you expect: it just compile, with g++ but not with other compiler likely, see comment in code)