why std::map throws an exception? - c++

I run this code using both gpp and microsoft compiler but in both case I'v got an exception
but I can't understand why!
this is my code:
#include <iostream>
#include <map>
using namespace std;
map<int,int> fib;
int fibo(int i)
{
if (!fib.count(i))
{
fib.insert(pair<int, int>(i,fibo(i-1)+fibo(i-2)));
}
return fib[i];
}
int r(int i)
{
if(i<3)
{
return i;
}
else
{
return fibo(i)+r(i-2);
}
}
int main()
{
fib.insert(pair<int, int>(0,1));
fib.insert(pair<int, int>(1,1));
int a,b,n;
cin>>a>>b;
n=b-a;
int fiba=fibo(a);
int fibaa=fibo(a-1);
cout << (r(n+1)*fiba)+(r(n)*fibaa);
return 0;
}
can anyone help me?
I debugged this code and I found that fib.insert(pair<int, int>(i,fibo(i-1)+fibo(i-2))); doesn't work.

I've got Stack Overflow exception when I ran your code, obviously because of too deep recursion.
You should either increase stack size (but you can later choose to input a larger number and get the same exception again), or convert this algorithm into a non-recursive one (for example see this one: http://www.codeproject.com/Tips/109443/Fibonacci-Recursive-and-Non-Recursive-C)

Did you try to input some negative numbers? You don't do any check on the inputs you pass to your program, and in
return fib[i];
you will receive an error if you try to access non-existent locations.

Related

Giving the change using a "greedy "method - what(): std::bad_allock

After expanding my program to include change such as 0.01,0.02,0.05,0.1,0.2,0.5 (zł) I was given:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Process returned 3 (0x3) execution time : 56.358 s
Press any key to continue.
It isn't the first time I have gotten this message, but it only happens upon using vectors.
The program would be working fine had I refrained from adding the update, but I'm curious as to why this message pops out, and what the cause of it may be. I suppose it has to do with the bad placement of something in the memory?
Thank you for your help people.
#include <iostream>
#include <vector>
using namespace std;
int main(){
int iloscMonet=9;
double monety[iloscMonet]={0.01,0.02,0.05,0.1,0.2,0.5,1,2,5};
double resztaDoWydania=4.01;
int licznikMonet=0;
vector <int> jakieMonety;
while(resztaDoWydania){
int nominal = 0;
for(int i=0;i<iloscMonet;i++){
if((monety[i]<=resztaDoWydania)&&(monety[i]>nominal)){
nominal=monety[i];
}
}
resztaDoWydania-=nominal;
jakieMonety.push_back(nominal);
licznikMonet++;
}
cout<<"ile monet?: "<<licznikMonet<<endl;
cout<<"jakie monety?: ";
for(int i=0;i<jakieMonety.size();i++){
cout<<jakieMonety.at(i)<<" ";
}
return 0;
}
Calculation of floating-point number may contain errors.
When I add #include <cstdio> in top of your code and printf("%.30f\n", resztaDoWydania); after licznikMonet++;, I found that the value of resztaDoWydania stacking at 0.009999999999999786837179271970.
You should avoid using floating-point numbers as much as you can.
In this case, you can multiply each of the values by 100 to make them integers.
#include <iostream>
#include <vector>
using namespace std;
int main(){
int iloscMonet=9;
int monety[iloscMonet]={1,2,5,10,20,50,100,200,500};
int resztaDoWydania=401;
int licznikMonet=0;
vector <int> jakieMonety;
while(resztaDoWydania){
int nominal = 0;
for(int i=0;i<iloscMonet;i++){
if((monety[i]<=resztaDoWydania)&&(monety[i]>nominal)){
nominal=monety[i];
}
}
resztaDoWydania-=nominal;
jakieMonety.push_back(nominal);
licznikMonet++;
}
cout<<"ile monet?: "<<licznikMonet<<endl;
cout<<"jakie monety?: ";
for(int i=0;i<jakieMonety.size();i++){
cout<<jakieMonety.at(i)<<" ";
// if you want outpuf of floating-point numbers as the original
//cout<<(jakieMonety.at(i)/100.0)<<" ";
}
return 0;
}
try while(resztaDoWydania>0)

What is the problem with the following code using constructors for sorting strings?

#include <iostream>
#include <string.h>
using namespace std;
class sorting
{
private:
char str[10];
public:
sorting() {
int i;
for(i=0;i<10;i++) {
cin>>str[i];
}
}
void sort() {
int i,j;
char temp;
for(i=0;i<10;i++) {
for(j=i+1;j<10;j++) {
if(strcmp(str[j],str[j+1])>0) {
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
for(i=0;i<10;i++) {
cout<<str[i];
cout<<"\n";
}
}
};
int main() {
sorting s1;
cout<<s1.sort();
return 0;
}
This is a code I have written to sort strings using constructors. It gives me error in the if condition of the code where I have used strcmp. Please review this for I could not get the desired output and it gives me errors.
Problem 1
Like someone already pointed out, you cant use strcopy on chars. If you want to create a string array i would suggest using either char** or std::string*.
Problem 2
In your nested loop you will get an index out of bounds error, due to the fact that once i reaches a value of 8, j will be 9, which means that when you try to access str[j+1] which evaluates to str[10], you will get said error.

Why does the program to find the largest number formed using elements of an array not work?

Visit https://www.interviewbit.com/problems/largest-number/ for the question...
Now I wrote the below code to solve the question (although I used an array to store the number, will do the storing in strings part later..)-
So in this algorithm, I basically used quicksort but with a twist, I changed the definition of greater than or lesser than of two numbers say X, Y such that if the number formed by using X first and Y second or XY is >= YX then greater than(X, Y) is true
In the present scenario, the code is giving runtime error, which I can't understand why, also after a bit of debugging as shown in the comments, still the answer is not coming as expected.
#include <iostream>
#include <vector>
#include <cmath>
#include <stdlib.h>
#include <time.h>
using namespace std ;
bool greaterthan(int a,int b)
{
int n1,n2,s1,s2;
n1=((int )log10(a))+1;
n2=((int)log10(b))+1;
s1=a*((int )pow(10,n2))+b;
s2=a + ((int )pow(10,n1))*b;
if(s1>=s2){return true;}
else{return false;}
}
int spartitions(vector<int >&B,int s , int e)
{
int pivot = B[e];
int pin =s;
int i;
for(i=s;i<=e;i++) //if i change this to i<e
{
if(B[pin]>=pivot)
{swap(B[pin],B[i]);
pin++;
}
// and add swap(B[pin],B[e]);
}
return pin-1; // and return pin here then it works but not give correct output
}
int prand(vector<int >&B,int s ,int e)
{
srand(time(NULL));
int n = rand()%(e-s+1)+s;
swap(B[n],B[e]);
int pin = spartitions(B,s,e);
return pin;
}
void qsort(vector<int >&B,int s, int e )
{
if(s<e){
int p= prand(B,s,e);
qsort(B,s,p-1);
qsort(B,p+1,e);
}
}
vector<int> largestnumber(vector<int >&A)
{
int n =A.size();
vector<int >B(n);
B=A;
qsort(B,0,n-1);
return B;
}
int main()
{
int n;
cin>>n;
vector<int>A(n);
int i;
for(i=0;i<n;i++)
{
cin>>A[i];
}
vector<int >B(n);
B=largestnumber(A);
for(i=0;i<n;i++)
{
cout<<B[i];
}
}
Please Help as I am a newbie in programming and can't figure this out from like 3-4 hours ...??
Would really appreciate if someone can correct my code only and not give a different algorithm, as I want this algorithm to be corrected.
Your self-written qsort function recursively calls itself, which adds more things to the stack, which only has so much space. When the list is too big, there will be too many function calls in the stack and it overflows. That's why anything less than 5 for the first input (which is for n) works fine but as soon as you exceed that, you get a runtime error. Consider not using a recursive function call.
Edit: Enabling optimisation also seems to fix this issue.
This may not work depending on the compiler and how it optimises. (Works on MSVC)

SIGABRT:out of range when using stoi/stol

//I'm trying to solve this problem from HackerEarth: Binary Queries.
Though initially, the problem sounds easy to me but when actually submitted my code to run on all the test cases, my code is throwing SIGABRT error.
Upon checking the error, I found the error to be of type out of range. I'm unable to figure out how to resolve this:
problem: https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/range-query-2/
#include<iostream>
#include<algorithm>
#include<cctype>
using namespace std;
int main()
{
long N,Q,L,R,X;
int ch=0,buf;
unsigned long long intrim;
string str,cstr;
scanf("%ld %ld",&N,&Q);
cin.ignore();
getline(cin,str);
str.erase((remove_if(str.begin(),str.end(),(int(*)(int))isspace)),str.end()); // here its a key point
//cout<<str;
for(int i=0;i<Q;i++)
{
scanf("%d",&ch);
if(ch==1) // alter the X bit
{
scanf("%ld",&X);
if(str[X-1]==0){
str[X-1]=1;
}
else {
str[X-1]=0;
}
}
else if(ch==0)
{
scanf("%ld %ld",&L,&R);
cstr.append((str.begin()+L-1),str.begin()+R);
intrim=std::stoull(cstr,nullptr,2);
if(intrim%2==0){
cout<<"EVEN"<<endl;
}
else{
cout<<"ODD"<<endl;
}
cstr.clear();
}
}
}
stoi return an integer number
stol return a long int number
stoll return a long long int number
So, when you are converting a string to a number, thought about the possible range and use accordingly.

How can I fix a SPOJ time limit exceeded error on the STAMPS challenge?

Here is the link for the problem: http://www.spoj.com/problems/STAMPS/;
here is the ideone link for the current code: http://ideone.com/AcHfc6;
here is the code:
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
int t,x,n,sum,sum2,count,i,j;
scanf("%d",&t);
for(j=1;j<=t;j++)
{
cin>>x>>n;
sum=0;
int offer[n];
for(i=0;i<n;i++)
{
cin>>offer[i];
sum+=offer[i];
sort(offer,offer+n);
}
if(sum>=x)
{
sum2=0;
count=0;
for(i=n-1;i>=0;i--)
{
sum2+=offer[i];
if(sum2<=x)
count++;
else
break;
}
cout<<"Scenario #"<<j<<":"<<endl;
cout<<count<<endl;
cout<<endl;
}
else
{
cout<<"Scenario #"<<j<<":"<<endl;
cout<<"impossible"<<endl;
cout<<endl;
}
}
return 0;
}
The code gives the right answers for the given test cases but it causes TLE. I've tried converting my cin's and cout's to scanf/printf but, weirdly enough, the answers were not the same and I don't know how the answers were different from each other.
What's going wrong?
I suspect your main problem is here:
for(i=0;i<n;i++)
{
cin>>offer[i];
sum+=offer[i];
sort(offer,offer+n);
}
You sort the data for every number that's entered. Also, you sort random data because you only have i rows of valid data in the array, not n rows. The sort should be done once, outside the loop:
for(i=0;i<n;i++)
{
cin>>offer[i];
sum+=offer[i];
}
sort(offer,offer+n);