No output when merge function is called - c++

I have a doubt in the following code. Can somebody please explain.
using namespace std;
#define INT_SIZE 32
#define R 4
#define C 4
#define N 4
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<limits.h>
#include<stack>
#include<vector>
#include<algorithm>
struct interval{
int start;
int end;
};
bool compareInterval(interval i1, interval i2)
{
return (i1.start < i2.start)? true: false;
}
int merge(vector<interval>& a, int n)
{
stack<interval> s;
sort(a.begin(), a.end(), compareInterval);
s.push(a[0]);
int i=1;
interval temp;
while(i<n)
{
temp = s.top();
s.pop();
if(temp.end > a[i].start && a[i].end > temp.end)
{
temp.end = a[i].end;
s.push(temp);
}
else if(temp.end < a[i].start)
{
s.push(temp);
s.push(a[i]);
}
i++;
}
while(s.size())
{
temp = s.top();
cout << temp.start << " ";
cout << temp.end << "\n";
s.pop();
}
return 0;
}
int main()
{
interval intvls[] = { {6,8}, {1,9}, {2,4}, {4,7} };
vector<interval> intervals(intvls, intvls+4);
for(int i=0;i<4;i++)
{cout << intervals[i].start;
} // This output is not coming when merge function is called
cout << merge(intervals, 4);
}
My doubt is "When I comment the merge function call i.e
// cout << merge(intervals, 4);
When I comment this line, then I am able to see output of cout<<intervals[i].start.
Otherwise, I am not able to see the output.
"

You are not ending your output with a newline. Try:
{cout << intervals[i].start << "\n";}
Without the newline, this output is probably getting hidden amongst all the output produced by merge().

There are few issues with this code.
s.push(a[0]); <-- Only on element is in you stack.
//s.push(a[1]).. you will have to add all other elements like this.
while(i<n)
{
temp = s.top(); <-- for second i s will be empty. Here you must check if stack is empty before getting top element.
s.pop();
}
Your first output is not printed correctly. use std::endl
cout << intervals[i].start << endl;

There is a bug in merge that leads to a segmentation fault. Due to this std::cout is not flushed. If you comment out the line with the merge call, std::cout is flushed when the program exits.

Related

Comparison behavior of ' <' operator

Why is this printing "Popescu" instead of "Ionescu", since "Popescu" > "Ionescu"?
#include <iostream>
using namespace std;
int main(){
char v[3][100] = {"Popescu","Ionescu","Vasilescu"};
if(v[0]<v[1]){
cout << v[0];
}else{
cout << v[1];
}
return 0;
}
Since char[100] doesn't have an operator<, you fall back to operator< for char*. That was not what you intended - it returns the first object in memory. And v[0] definitely precedes v[1].
You want std::string, where operator< is overloaded to do what you want.
Your Initialization is wrong that is why print 'Popescu'
First You need to clear about your array position that is main criteria before start work on your program see my image
see below example:
char always take one character:
#include <iostream>
using namespace std;
int main(){
char v[3][3] =
{
{'p','I','l'},
{'s','e','r'},
{'q','w','x'}
};
cout<< v[0][0]; //print the array2d
return 0;
}
output:
p
First Condition:
#include <iostream>
using namespace std;
int main(){
char v[3][100] = {"p","I","l"};
if(v[0][0]==v[0][0])
{
//cout << v[0]; //when uncomment this line output is p
cout << v[1]; **see here print the i because check the position of array image**
}
else
{
cout << v[1];
}
return 0;
}
output: I //now the position of your array see below
Now the second Condition:
int main(){
char v[3][100] = {"p","I","l"};
if(v[1]==v[1])
{
// cout << v[0];
cout << v[1];
}
else
{
cout << v[1];
}
return 0;
output:
I
If the above criteria Understood then Come To your main problem:
#include <iostream>
using namespace std;
int main(){
char v[3][100] = {"p","I","l"};
if(v[0]<=v[1])
{
cout << v[0];
// cout << v[2];
}
else
{
cout << v[1];
}
return 0;
}
output: p
I hope my answer is understood.

C++ string size changing during loop

My Program is suppose to read a string and then insert each character into the stack. I noticed when I print the length, which is the size of the word, it changes to some high number. For example: word = "hello" length will = 5 at first but eventually change to = 111. Also When I use 2 letters I always get a segmentation fault. What is causing this? Why is the length of the word changing?
#include <iostream>
#include <string>
#include "Stack.h"
using namespace std;
int main()
{
Stack stack;
string word;
cout << "Enter word: ";
getline(cin, word);
cout << word << "|" << endl;
int length = word.size();
for (int i = 0; i < length; i++) {
cout << "i: " << i << "\tlength: " << length << endl;
stack.push(word[i]);
cout << "TOP: " << stack.top() << endl;
}
while (!stack.isEmpty())
{
cout << stack.pop();
}
cout << endl;
return 0;
}
#include <iostream>
#include <string>
#define STACK_CAPACITY 1000
using namespace std;
class Stack
{
private:
int topIndex;
char arr[];
public:
// Constructor
Stack()
{
arr[STACK_CAPACITY];
topIndex = -1;
}
// adds elements to "top" of array
void push(char c)
{
// if stack is full, do not add
if (isFull())
{
cout << "Push on full Stack" << endl;
// terminate function
}
topIndex++;
arr[topIndex] = c;
}
// Removes last inserted (push) element from the stack and returns it
char pop()
{
// checks if Stack is empty
if (isEmpty())
{
cout << "Pop on empty Stack" << endl;
return '#';
}
// if not empty, remove and return last element inserted
char temp = arr[topIndex];
arr[topIndex--] = ' ';
return temp;
}
// Returns but does not remove last inserted (push) element
char top() { return arr[topIndex]; }
// Utilities
bool isEmpty() { return topIndex == -1; }
bool isFull() { return topIndex == STACK_CAPACITY - 1; }
int size() { return topIndex + 1; }
// Destructor
~Stack()
{
}
}
There are various problems in your Stack class that cause it to exhibit undefined behaviour.
For example, in the constructor
Stack()
{
arr[STACK_CAPACITY];
topIndex = -1;
}
does not (as, I guess, you are expecting) resize arr to have STACK_CAPACITY elements. It attempts to evaluate the value of arr[STACK_CAPACITY] which, since arr is declared as char arr[], does not exist. Hence that statement has undefined behaviour.
Similarly, the push() member function
// adds elements to "top" of array
void push(char c)
{
// if stack is full, do not add
if (isFull())
{
cout << "Push on full Stack" << endl;
// terminate function
}
topIndex++;
arr[topIndex] = c;
}
attempts (on the first call) to modify arr[0] - which also does not exist.
When behaviour is undefined - as it is in the above - anything can happen. Including appearing to overwrite unrelated data or (in your case) overwriting parts of the string word in main().
You need to read up better on the basics of C++, rather than guessing about how things work. You have guessed VERY incorrectly.

Heap Corruption at class destructor?

I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong.
I wrote a c++ code with class implementing a simple stack, trying to push and pop random stream of characters. It seems to work fine, but at the end of the file, it produces some sort of runtime error:
HEAP CORRUPTION DETECTED: after Normal block....
Since the error occurs at the end of the file, my guess is that there is a problem at deleting the pointer(class destructor). However, I have no idea what is wrong with the destructor I wrote.
Also, after some trial and error, I found out that if I address a bigger number to unsigned integer value iter1 (ex: 80), the runtime error does not occur. Could you explain what is the problem here, and how to bypass it?
stack.h:
class sstack
{
public:
sstack(int length = 256);
~sstack(void);
int sstackPop(char &c);
int sstackPush(char c);
bool isempty();
bool isFull();
protected:
private:
char *sstackBuffer;
int sstackSize;
int sstackIndex; // Initial = -1
};
stack.cpp:
#include "stack.h"
#include <iostream>
using namespace std;
sstack::sstack(int length)
{
sstackIndex = -1;
if (length > 0)
sstackSize = length;
else
sstackSize = 256;
sstackBuffer = new char[sstackSize];
}
sstack::~sstack(void)
{
delete[] sstackBuffer;
}
bool sstack::isempty()
{
if (sstackIndex < 0)
{
cout << "is empty!(isempty)" << endl;
return 1;
}
else
return 0;
}
bool sstack::isFull()
{
if (sstackIndex >= sstackSize)
return 1;
else
return 0;
}
int sstack::sstackPop(char &c)
{
if (!isempty())
{
c = sstackBuffer[sstackIndex--];
cout << sstackIndex << endl;
return 1;
}
else
{
cout << "is empty!(sstackPop)" << endl;
return 0;
}
}
int sstack::sstackPush(char c)
{
if (!isFull())
{
sstackBuffer[++sstackIndex] = c;
return 1;
}
else{
return 0;
}
}
main.cpp:
#include <iostream>
#include "stack.h"
#include <string>
using namespace std;
int main(){
unsigned int iter1 = 5;
unsigned int iter2 = 800;
sstack stackDefault;
sstack stack1(iter1);
sstack stack2(iter2);
char buffer[80];
memset(buffer, 0x00, 80);
char BUFFER[80] = "A random stream of characters";
strcpy_s(buffer, 80, BUFFER);
for (int i = 0; i< strlen(buffer); i++)
{
cout << " stack1: " << stack1.sstackPush(buffer[i]);
cout << " stack2: " << stack2.sstackPush(buffer[i]);
cout << " stackD: " << stackDefault.sstackPush(buffer[i]);
cout << " i : "<< i << endl;
}
cout << "out of Pushes" << endl;
int i = 0;
memset(buffer, 0x00, 80);
while (!stack1.isempty())
stack1.sstackPop(buffer[i++]);
cout << buffer << endl;
getchar();
}
sstackBuffer[++sstackIndex] = c;
Will write past the end of sstackBuffer when the stack only has one element left.
If you consider a stack of size 1. In the first call to push that line would evaluate to:
sstackBuffer[1] = c;
Which is beyond the memory you've allocated.
Be sure you're aware of the difference between pre-increment and post-increment operators. By your code example I would suggest you use post-increment in push and pre-increment in pop.

I have written a C++ program to print permutations of letters of a word. I want to know are there other simpler ways to do it?

Here is the code. I have used a self calling function to create a nested loop of exact size(that is determined by the length of word entered by user) neccessary.
I took me about 5hrs to write it and debug it. Have I over did it? Are there any other simpler ways to do it without using any specifically designed c++ library functions?
//PROGRAM TO PRINT ALL PERMUTAIONS OF LETTERS OF A WORD
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
char a[11],p[11]; //a to store the word entered
int flag; //p to store a permutaion untill it is printed
void permute(int* chk,int n ,int pos)
{ int i,j,k;
int nxtchk[10];
flag=1;
for(i=0; i<n ; i++ )
{ for(j=0;j<n;j++)
nxtchk[j]=1;
if(chk[i])
{
p[pos]=a[i];
chk[i]=0;
for(j=0;j<=pos;j++)
for(k=0;k<n;k++)
if(p[j]==a[k])
nxtchk[k]=0;
if(pos+1<n)
permute(nxtchk,n,pos+1);
}
}
if(flag) //flag used to ensure each permutation is printed once only
{ cout<<p<<" "; flag=0; }
}
int main()
{
int chk[10]={1,1,1,1,1,1,1,1,1,1};
cout<<"Enter a word whose letters are all different: "; gets(a);
int n=strlen(a);
p[n]='\0';
permute(chk,n,0);
}
You can look at std::next_permutation:
// next_permutation example
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort
int main() {
int myints[] = { 1,2,3 };
std::sort(myints, myints + 3);
std::cout << "The 3! possible permutations with 3 elements:\n";
do {
std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
} while (std::next_permutation(myints, myints + 3));
std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
return 0;
}
You may also want to browse this article: C++ Algorithms: next_permutation().
It is a variant of permutation without any specifically designed library functions (except std::swap but this can be easily substituted by code)
#include <iostream>
#include <vector>
#include <list>
#include <iterator>
void permute(std::vector<int> a, int i, int n)
{
int j;
if (i == n) {
std::copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout<<'\n';
}
else
{
for (j = i; j <= n; j++)
{
std::swap(a[i], a[j]);
permute(a, i+1, n);
std::swap(a[i], a[j]);
}
}
}
int main()
{
std::vector<int> v = { 5,7,3,8 };
permute(v, 0, v.size() -1 );
return 1;
}
also possible to use prev_permutation

How can I modifiy my c++ program to show a word inputted by a user, backwards using a stack?

I want to assign a pointer to every character the user inputs. Then in doing so, I probably can use a loop to store the characters and a second loop rearrange the stack order using the pointers. But I don't know how to write that in a program form, and I'm not sure if it can work. Here is what I have so far:
#include<iostream>
using namespace std;
class Stack{
public:
enum {MaxStack = 50};
void init() {top = -1;}
void push( char n ){
if ( isFull() ) {
cerr << "Full Stack. DON'T PUSH\n";
return;
}
else {
arr[ ++top ] = n;
cout << "Just pushed " << n << endl;
return;}
}
int pop() {
if (isEmpty() ) {
cerr << "\tEmpty Stack. Don't Pop\n\n";
return 1;
}
else
return arr[top--];
}
bool isEmpty() {return top < 0 ? 1 : 0;}
bool isFull() {return top >= MaxStack -1 ? top : 0;}
void dump_stack() {
cout << "The Stack contents, from top to bottom, from a stack dump are: " << endl;
for (int i = top; i >= 0; i--)
cout << "\t\t" << arr[i] << endl;
}
private:
int top;
int arr[MaxStack];
};
int main()
{
Stack a_stack;
int x = 0;
char inputchar;
cout<<"Please enter a word"<<endl;
a_stack.init();
while (inputchar != '.') //terminating char
{
cin >> inputchar;
array[x] = inputchar;
x++;
}
int j = x;
for (int i = 0; i < j; i++)
{
cout << array[x];
x--;
}
a_stack.push();
a_stack.dump_stack();
return 0;
}
A stack, by its very LIFO nature (Last In, First Out), will reverse the order of anything you put in it. Example for string "Hello":
(The top of the stack is to the left)
H push "H"
eH push "e"
leH push "l"
lleH push "l"
olleH push "o"
Now when you pop from the stack, you'll first get "o", then "l", etc. It's whatever you put in but in reverse order. You don't need to do anything special to achive that. Just push to stack in normal order, and when you pop you'll get it reversed:
// while loop
{
cin >> inputchar;
a_stack.push(inputchar);
}
// Display in reverse
while (not a_stack.isEmpty()) {
cout << (char)a_stack.pop();
}
Here's a small example program using std::stack:
(No input error checking is done here.)
#include <iostream>
#include <stack>
int main()
{
std::stack<char> st;
char c = '\0';
while (c != '.') {
c = std::cin.get();
st.push(c);
}
while (not st.empty()) {
std::cout << st.top();
st.pop();
}
std::cout << '\n';
}
Example input and output:
Hello world.
.dlrow olleH
Unless using a stack is a must (i.e. it is a homework), you might be better off with getline(), its parameter delim (cf getline) followed by a reverse loop over the array. It would be faster, cleaner, less prone to errors and basically a two-liner.