return statement not returning values [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
emp* emp::check(string a,emp* ceo)
{
emp* l;
employee* b;
l=ceo;
if(l->name==a)
{
cout<<l->name;
return l;
}
b=l->j;
while (b!=NULL)
{
check(a,b->junior);
b=b->next;
}
}
void main()
{
l = check(d,ceo);
cout<<l->name;
}
now initially the value of l->name is being printed but finally in main value of l is not being returned.
this means that it is reaching the return statement but l is not being returned.
can someone explain why?

What is happening is this, it is matching in one of the recursive calls to check and you then discard the return value. You need to change the function to look like this:
emp* emp::check(string a,emp* ceo)
{
emp* l;
employee* b;
l=ceo;
if(l->name==a)
{
cout<<l->name;
return l;
}
b=l->j;
while (b!=NULL)
{
l = check(a,b->junior); // <----- line changed
if (l)
return l; // If we found something, return it.
b=b->next;
}
return 0; // <----- Always return a value
}
Also, there are various stylistic issues with your code, it would be clearer if you made changes something like this so that your variable and function names are useful:
emp* emp::findEmployeeByName(string name,emp* root)
{
if(root->name==a)
{
cout<<root->name;
return root;
}
// What on earth is ->j? Give your members meaningful names
for (employee* worker=l->j; worker; worker = worker->next)
{
emp* match = findEmployeeByName(name,worker->junior); // <----- line changed
if (match)
return match; // If we found something, return it.
}
return 0; // <----- Always return a value
}

Related

What's the difference b/w map[key] vs map.count(key) ? (particularly in this code) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
So I was Solving a leetcode Problem and one dumb mistake made in debugg for more than an hour.
Leetcode Question
Answers(both working and not working)
Working code:
`
class Solution {
public:
int longestPalindrome(vector<string>& words) {
unordered_map<string,int> map;
for(string s:words){
map[s]++;
}
bool isOdd = false;
int ans = 0;
for(auto i:map){
string rv = i.first;
reverse(rv.begin(),rv.end());
if(i.first[0]==i.first[1]){
if(i.second%2==0)
ans+=i.second;
else{
ans+= i.second-1;
isOdd = true;
}
}
else if(i.first[0]<i.first[1] && map.count(rv)){
ans += 2*min(i.second,map[rv]);
}
}
if(isOdd){
ans++;
}
return 2*ans;
}
};
Not working code:
`
class Solution {
public:
int longestPalindrome(vector<string>& words) {
unordered_map<string,int> map;
for(string s:words){
map[s]++;
}
bool isOdd = false;
int ans = 0;
for(auto i:map){
string rv = i.first;
reverse(rv.begin(),rv.end());
if(i.first[0]==i.first[1]){
if(i.second%2==0)
ans+=i.second;
else{
ans+= i.second-1;
isOdd = true;
}
}
else if(i.first[0]<i.first[1] && map[rv]){
ans += 2*min(i.second,map[rv]);
}
}
if(isOdd){
ans++;
}
return 2*ans;
}
};
The only difference between both code is map[rv] ==> map.count(rv)
test case which is giving error:
["oo","vv","uu","gg","pp","ff","ss","yy","vv","cc","rr","ig","jj","uu","ig","gb","zz","xx","ff","bb","ii","dd","ii",
"ee","mm","qq","ig","ww","ss","tt","vv","oo","ww","ss","bi","ff","gg","bi","jj","ee","gb",
"qq","bg","nn","vv","oo","bb","pp","ww","qq","mm","ee","tt","hh","ss","tt","ee","gi","ig","uu","ff","zz",
"ii","ff","ss","gi","yy","gb","mm","pp","uu","kk","jj","ee"]
Can anyone please help me?
I've tried googling this stuff but couldn't find it. then i've tried asking few people on discord. but no progress.
I just wanna know why above(not working part) code in not working.
What is the deal with map[key] and map.count(key)?
When should i use which one?
std::map.count() will check, if an element with a given key exists. It will not modify the container. Please see here. It is even defined as constto indicate that fact.
The std::maps index operator is different. It
returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
So, if the key does not exist, it will add an entry to the map, with this new key.
Therefore your second code cannot work.
map[rv] isn't a regular getter. It inserts default element if key is not found.
so you mutate (unordered_map) map whereas you iterate on it (which (might) invalidate iterator, making you loop undefined behavior).

Trying to find leaf nodes in a Quadtree (C++) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I am making a Quadtree in C++. I need to find the leaf nodes of the tree. To do this I have this function that needs to return a vector of the leaf nodes. For now everything else seems to work, but this function doesn't and I don't understand why.
vector<QuadTree*> find_leaves(QuadTree* quad, vector<QuadTree*>& list_of_leaves) {
if (quad->is_leaf) {
list_of_leaves.push_back(quad);
}
else {
for (int i = 0; i < 4; i++) {
find_leaves(quad->children[i], list_of_leaves);
}
}
return list_of_leaves;
}
Before doing it in C++ I did it in Python (which I know much better). This function does the same thing but in Python and works just fine :
def find_leaves(quad, list_of_leaves = []):
if quad.is_leaf:
list_of_leaves.append(quad)
else:
for i in quad.children:
find_leaves(i, list_of_leaves)
return list_of_leaves
In both these codes quad is a node of the tree. Does anyone see where the error is, or does anyone know another way to find leaf nodes in a QuadTree? Thank you for your help.
You are returning an empty vector, a temporary instead of the original.
Try this instead:
void find_leaves(QuadTree* quad, vector<QuadTree*>& list_of_leaves) {
if (quad->is_leaf) {
list_of_leaves.push_back(quad);
}
else {
for (int i = 0; i < 4; i++) {
find_leaves(quad->children[i], list_of_leaves);
}
}
}

Parenthesis Checker gfgs [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The following code is giving segmentation fault can anyone tell why. this is a geeks for geeks practice problem (Parenthesis Checker) .
Q- Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return 'true' for exp = “[()]{}{()()}” and 'false' for exp = “[(])”.
bool check(string s)
{
stack<char> save;
int x = s.size();
for(int i=0;i<x;i++)
{
if(s[i]=='{' || s[i]=='['|| s[i]=='(')
{
save.push(s[i]);
}
else if(s[i]=='}'){
if(save.top()=='{')
{
save.pop();
}
else{
return false;
}
}
else if(s[i]==']')
{
if(save.top()=='[')
{
save.pop();
}
else{
return false;
}
}
else if(s[i]==')')
{
if(save.top()=='(')
{
save.pop();
}
else{
return false;
}
}
}
if(!save.empty())
{
return false;
}
else{
return true;
}
}
You have a chance to seg-fault when the stack is empty and the next character in the string is a closing paren.
E.g. if the input string is ")" or "())" your program will not behave as intended.
You will need to change the if statements from
if (save.top() == '('){...} to if (!save.empty() && save.top() == '('){...}
And similarly for every other case where you check save.top (The preceeding code does not guarantee that the stack is not empty at that given point).
Note: You would also need to do this for each occurrence of pop as well, but the guards before top() will guarantee that the stack is not empty when you then pop.

longest common substring in array of strings runtime problem [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
string longestCommonPrefix(vector<string>& strs) {
string res = "";
int i, j;
bool flag = true;
for(int i=0; i<strs[0].size(); i++)
{
for(int j=0; j<strs.size()-1; j++)
{
if(strs[j][i] == strs[j+1][i])
{
flag = true;
}
else
return res;
}
if(flag == true)
{
res += strs[0][i];
}
}
return res;
}
I was doing this leetcode question where we had to find the longest common prefix of given array of strings and then i got stuck at this i cant understand what is the meaning of this error, most of the test cases are passed so i don't think logic is wrong.Is there any corner cases i am missing?
Runtime Error Message:
Line 924: Char 9: runtime error: reference binding to null pointer of type 'std::__cxx11::basic_string, std::allocator >' (stl_vector.h)
Last executed input:
[]
Thanks in advance
Its null pointer exception. So you should check if str is null i.e. str=='" for each string in vector.
and return answer accordingly.

Control reaches at the end of non-void function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am doing a question on Hackerrank ,but whenever I compile my code it shows control reaches at the end of non-void function .Here is my source code :
/*
Compare two linked lists A and B
Return 1 if they are identical and 0 if they are not.
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
int CompareLists(Node *headA, Node* headB)
{
if(headA==NULL&&headB==NULL)
{
return 1;
}
else if( headA!=NULL&&headB!=NULL)
{
while(headA!=NULL&&headB!=NULL)
{
if(headA->data==headB->data)
{
headA=headA->next;
headB=headB->next;
}
else
{
return 0;
exit (0);
}
return 1;
}
}
else
{
return 0;
}
}
Please tell how to rectify this and thanks in advance.
I can see two problems with reachability here. First the simple one:
{
return 0;
exit (0);
}
The exit call is unreachable. (That line is almost certainly a mistake. I can't think of any good reason to call exit there.)
Next the more complicated one ... that is the root cause of the compilation error:
while(headA!=NULL&&headB!=NULL)
{
if(headA->data==headB->data)
{
headA=headA->next;
headB=headB->next;
}
else
{
return 0;
exit (0);
}
return 1;
}
Look at where the return 1; is. It is INSIDE the loop.
So, what happens if headA != NULL && headB != NULL evaluates to false? In that case, the loop body with the return 1; at the end is skipped ... and you reach the end of the method.
Hence the compilation error.
I suspect that the "fix" is to move the return to after the loop, but I didn't try to understand the logic of your code, so that might be the wrong "fix".
What happens after this code executes?
if(headA->data==headB->data)
{
headA=headA->next;
headB=headB->next;
}
...if headA->next == NULL or headB->next == NULL?