I'm really new to DSA or basically just finished learning about Data Structures.
Tried this Hacker Rank problem (https://www.hackerrank.com/challenges/simple-text-editor/problem?isFullScreen=true) after solving a few of them already.
The problem here is after pushing a the first element in Stack, All the elements after that first element gets changed to the last added element.For e.g->
Push-> abcde,
Push-> de,
Push-> c,
Push-> ab
All the elements ab,c,de after abcde change to ab for some unknown reason.
I know there are/will be many simpler approaches than this one but I just wanna know what is wrong here.Any help would be appreciated since I'm a beginner. Thank you :)
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
struct Stack
{
char *arr[100][100];
int tos;
};
void push(struct Stack*,char*);
char *pop(struct Stack*);
int main() {
int i,place,j,Q,c;
char warr[100],Str[1000]="";
struct Stack S1,S2;
S1.tos=S2.tos=-1;
scanf("%d",&Q);
for(i=0;i<Q;i++)
{
scanf("%d",&c);
if(c==1)
{
fflush(stdin);
scanf("%s",warr);
strcat(Str,warr);
push(&S2,"1");
push(&S1,warr);
}
else if(c==2)
{
int k=0;
char warr[100]="";
scanf("%d",&place);
for(j=strlen(Str)-place;j<strlen(Str);j++)
{
warr[k]=Str[j];
k++;
}
warr[k]='\0';
push(&S2,"2");
push(&S1,warr);
Str[strlen(Str)-place]='\0';
}
else if(c==3)
{
scanf("%d",&place);
printf("%c\n",Str[place-1]);
}
else
{
if(strcmp(pop(&S2),"1")==0)
{
Str[strlen(Str)-strlen(pop(&S1))]='\0';
}
else
{
char *ch;
ch=pop(&S1);
strcat(Str,ch);
}
}
printf("string=%s\n",Str);
}
return 0;
}
void push(struct Stack *S,char *arr)
{
S->tos=S->tos+1;
S->arr[S->tos][99]=arr;
printf("pushed=%s\n",S->arr[S->tos][99]);
}
char* pop(struct Stack *S)
{
char* arr;
arr=S->arr[S->tos][99];
printf("popped=%s\n",S->arr[S->tos][99]);
S->tos=S->tos-1;
return arr;
}
Related
I'm still learning Modern C++ and I would like to clarify STD:FUNCTION,
Here is my sample code that works fine :
#include <iostream>
#include <functional>
using namespace std;
int func(function<bool()> foo) {
return 2;
}
struct fee {
bool operator()() {
return true;
}
};
int main() {
cout << func(fee());
}
It will display "2" on the console.
What I am wondering is why this does not work. I changed bool operator()() to bool operator()(int i).
#include <iostream>
#include <functional>
using namespace std;
int func(function<bool()> foo) {
return 2;
}
struct fee {
bool operator()(int i) {
return true;
}
};
int main() {
cout << func(fee());
}
The error says:
In function 'int main()':
18:20: error: could not convert 'fee()' from 'fee' to 'std::function<bool()>'
What should be the right thing to do ?
In the second example, the fee operator() function now takes an int as a parameter.
Therefore you need to change
int func(function<bool()> foo) {
return 2;
}
to
int func(function<bool(int)> foo) {
return 2;
}
to reflect that.
I keep getting this error. I know what function causes it, but don't know how to fix it. Looking up online from this post saying:
You need to pass a pointer to a dynamically allocated object, or make your own insde your chainLink class.
However, as I try to pass a string pointer. error still popping up. Here is my code.
#include <iostream>
#include "MWTNode.h"
#include "MWT.h"
using namespace std;
int main() {
MWT t;
string str ="abc";
string* strPtr = &str;
t.insert(strPtr);
std::cout << "Hello, World!" << std::endl;
return 0;
}
#include "MWTNode.h"
class MWT {
public:
MWTNode *root;
string find(const string &);
void insert(const string* string);
};
void MWT::insert(const string* word) {
MWTNode* curr = root;
MWTNode newNode;
string w = *word;
for (int i = 0; i < word->length(); i++) {
const char c = w[i];
if (curr->children.find(c) == curr->children.end()){
//curr->children[c]= MWTNode();
//node->frequency=node->frequency+1;
}
curr = &(curr->children[c]);
}
curr->flag = true;
}
#include <unordered_map>
#include <vector>
#include <string>
#include <sstream>
#include <set>
using namespace std;
class MWTNode {
public:
unordered_map<char, MWTNode> children;
string value;
bool flag;
int frequency;
MWTNode(const string &);
MWTNode(const char c);
MWTNode();
void setFrequency ();
int getFrequency ();
};
MWTNode::MWTNode(const string &val) {
value = val;
flag = false;
frequency = 0;
}
MWTNode::MWTNode(const char c) {
value =c;
flag = false;
frequency = 0;
}
MWTNode::MWTNode() {
value ="";
flag = false;
frequency = 0;
}
Lets highlight a few lines of the code you show
class MWT {
public:
MWTNode *root;
// ...
};
In that you declare the member variable root as a pointer.
void MWT::insert(const string* word) {
MWTNode* curr = root;
// ...
}
In the above you make curr point to where root is pointing.
But you never make root point anywhere! The MWT::root variable is uninitialized and will have an indeterminate value. Using this pointer in any way without initialization will lead to undefined behavior.
And yes you use this pointer, as you dereference curr inside the MWT::insert function.
It's a little unclear what you're doing (to me) but you need to make sure that root (and therefore curr) is a valid pointer before attempting to dereference it.
#include <stdio.h>
#include <stdlib.h>
struct linked {
int data;
struct linked *next;
}
*head,*ptr,*tmp;
void display(struct linked *head)
{
tmp=malloc(sizeof(struct linked));
tmp=head;
do
{
printf("%d ",tmp->data);
tmp=tmp->next;
} while(tmp->next!=NULL);
}
struct linked *createlist(struct linked *head)
{
int i,ch;
ptr=malloc(sizeof(struct linked));
//head=(struct linked *)malloc(sizeof(struct linked));
head=ptr=tmp=NULL;
printf("Enter number of elements you want in the list!");
scanf("%d",&ch);
printf("Enter the elements!\n");
for(i=0;i<ch;i++)
{
int ele;
tmp=malloc(sizeof(struct linked));
printf("Enter the element %d= ",i+1);
scanf("%d",&ele);
tmp->data=ele;
ptr->next=tmp;
ptr=tmp;
ptr->next=NULL;
if(head==NULL)
head=ptr;
}
return head;
}
int main(void)
{
// your code goes here
head=malloc(sizeof(struct linked));
head=createlist(head);
display(head);
return 0;
}
The problem here is i don't know whether I have allocated the memory correctly or is there any problem in my insertion of node. Please help i am new to this. Please give a suggestion about how do I debug the runtime errors in code how to find them where they are actually. Thanks.
EDIT: I got the error. First I was allocating memory needlessly. To head and ptr. Also in createlist() , I was using
createlist(struct linked *head)
calling as createlist(head)
from main().
This was leading to a call by value actually. That's why even after the creation of the list, the display() was not being called just because the head in createlist() was local to the function hence global head wasn't holding the front of the list. So, no way to traverse and that was generating the error.
Thanks for the help all.
Try this code instead of your code...
#include <stdio.h>
#include <stdlib.h>
typedef struct linked {
int data;
struct linked *next;
};
struct linked *head,*ptr,*tmp;
void display()
{
tmp=head;
do
{
printf("%d ",tmp->data);
tmp=tmp->next;
} while(tmp!=NULL);
}
void createlist()
{
int i,ch;
printf("Enter number of elements you want in the list!");
scanf("%d",&ch);
printf("Enter the elements!\n");
for(i=0;i<ch;i++)
{
int ele;
tmp=(struct linked*)malloc(sizeof(struct linked));
printf("Enter the element %d= ",i+1);
scanf("%d",&ele);
tmp->data=ele;
tmp->next=NULL;
if(head==NULL){
head=tmp;
ptr=head;
}
else{
ptr->next=tmp;
ptr=ptr->next;
}
}
//return head;
}
int main(void)
{
// head=malloc(sizeof(struct linked));
createlist();
display();
return 0;
}
While creating linked list you have to remember some cases..
1 - At first time when linked list is creating head is NULL and take action according to that
i.e code given in if condition in for loop
2 - after head node is got created you have to attach all the remaining node at the end of last created linked list
i.e code given in else condition in for loop
And if your creating a global variables then no need to pass those variable as a argument to the function
Global variables are visible to each and every function.
I am trying to implement lock free queue of user defined data type using boost library, but I am getting wrong result.
Please help me out where I am doing wrong.
#include <boost/lockfree/spsc_queue.hpp>
#include <thread>
#include <iostream>
#include <string.h>
#include <time.h>
class Queue
{
private:
unsigned char *m_data;
int m_len;
public:
Queue(unsigned char *data,int len);
Queue(const Queue &obj);
~Queue();
Queue & operator =(const Queue &obj);
unsigned char *getdata()
{
return m_data;
}
int getint()
{
return m_len;
}
};
Queue::Queue(unsigned char* data, int len)
{
m_len=len;
m_data=new unsigned char[m_len];
memcpy(m_data,data,m_len);
}
Queue::Queue(const Queue& obj)
{
m_len= obj.m_len;
m_data=new unsigned char[m_len];
memcpy(m_data,(unsigned char *)obj.m_data,m_len);
}
Queue::~Queue()
{
delete[] m_data;
m_len=0;
}
Queue & Queue::operator =(const Queue &obj)
{
if(this != &obj)
{
m_len=obj.m_len;
m_data=new unsigned char[m_len];
memcpy(m_data,(unsigned char *)obj.m_data,m_len);
}
return *this;
}
boost::lockfree::spsc_queue<Queue*> q(10);
void produce()
{
int i=0;
unsigned char* data=(unsigned char *)malloc(10);
memset(data,1,9);
Queue obj(data,10);
Queue *pqueue=&obj;
printf("%d\n",pqueue->getint());
q.push(pqueue);
}
void consume()
{
Queue *obj;
q.pop(&obj);
printf("%d\n",obj->getint());
}
int main(int argc, char** argv) {
// std::thread t1{produce};
// std::thread t2{consume};
//
// t1.join();
// t2.join();
produce();
consume();
return 0;
}
As per boost::lockfree::queue requirements I created following in class.
Copy Constructor
Assignment Operator
Destructor
Please let me know if anything other requires.
Thanks.
You're using malloc in C++.
You die.
You have 2 lives left.
Seriously, don't do that. Especially since using it with delete[] is clear cut Undefined Behaviour.
Sadly you lose another life here:
Queue obj(data,10);
Queue *pqueue=&obj;
q.push(pqueue);
You store a pointer to a local. More Undefined Behaviour
You have 1 life left.
Last life at
q.pop(&obj);
You pop using an iterator. It will be treated as an output iterator.
You get a return that indicates the number of elements popped, and items
will be written to &obj[0], &obj[1], &obj[2], etc.
Guess what? Undefined Behaviour.
See also: Boost spsc queue segfault
You died.
You're already dead. But you forsake your afterlife with
printf("%d\n",obj->getint());
Since pop might not have popped anything (the queue may have been empty), this in itself is Undefined Behaviour.
The funny part is, you talk about all these constructor requirements but you store pointers in the lockfree queue...?! Just write it:
typedef std::vector<unsigned char> Data;
class Queue {
private:
Data m_data;
public:
Queue(Data data) : m_data(std::move(data)) {}
Queue() : m_data() {}
unsigned char const *getdata() const { return m_data.data(); }
size_t getint() const { return m_data.size(); }
};
boost::lockfree::spsc_queue<Queue> q(10);
Live On Coliru
Notes:
you need to make the consumer check the return code of pop. The push might not have happened, and lock free queues don't block.
you don't need that contraption. Just pass vectors all the way:
C++ Code
Live On Coliru
#include <boost/lockfree/spsc_queue.hpp>
#include <thread>
#include <iostream>
#include <vector>
typedef std::vector<unsigned char> Queue;
boost::lockfree::spsc_queue<Queue> q(10);
void produce() {
Queue obj(10, 1);
std::cout << __FUNCTION__ << " - " << obj.size() << "\n";
q.push(std::move(obj));
}
void consume() {
Queue obj;
while (!q.pop(obj)) { }
std::cout << __FUNCTION__ << " - " << obj.size() << "\n";
}
int main() {
std::thread t1 {produce};
std::thread t2 {consume};
t1.join();
t2.join();
}
#include <stdio.h>
#include <string.h>
#define MAXN 15
char forbid[MAXN][MAXN];
int dp[2][1<<MAXN],c[1<<MAXN],*dp1,*dp2;
int cnt_one(int x)
{
int s=0;
while(x)
{
s++;
x&=x-1;
}
return s;
}
int main()
{
int t,n,s,a,b,i,j,k;
/*This is my use of freopen function*
************************************/
freopen("datain.txt","r",stdin);
freopen("dataout.txt","w",stdout);
/*This is just a dynamic program to solve a mathematical problem*
****************************************************************/
for(i=0;i<(1<<MAXN);i++) c[i]=cnt_one(i);
scanf("%d",&t);
while(t--)
{
memset(forbid,0,sizeof(forbid));
memset(dp[0],0,sizeof(int)*(1<<MAXN));
dp[0][0]=1;
scanf("%d%d",&n,&s);
while(s--)
{
scanf("%d%d",&a,&b);
forbid[a][b]=1;
}
for(i=1;i<=n;i++)
{
if(i%2)
{
dp1=dp[0];
dp2=dp[1];
}
else
{
dp1=dp[1];
dp2=dp[0];
}
memset(dp2,0,sizeof(int)*(1<<MAXN));
for(j=0;j<(1<<n);j++)
{
if(c[j]!=i-1) continue;
for(k=0;k<n;k++)
{
if(!(j>>k&1)&&!forbid[i][n-k]) dp2[j^(1<<k)]+=dp1[j];
}
}
}
printf("%d\n",dp2[(1<<n)-1]);
}
return 0;
}
This is my program.I used a dynamic program method to solve a mathematical problem.
But when I used the "freopen" function to redirect the "stdout" stream to the file of "dataout.txt",it failed and the file had no data in it.
Could you tell me why I can get the data from "datain.txt" but I can't output data into "dataout.txt"?Is there something wrong with my "freopen" function for "stdout" stream?
I think the problem is that you have a segmentation fault that you will not see. If you place a printf and a return after the freopen I think it will work (works for me).
I would recommend you to use "valgrind" on the resulting executable compiled for debug to see at what line the program crashes. If you want someone to help you further, you need to provide an example input.