I was trying to write code for vertical order traversal of a tree and my code prints the result on code::blocks however it is not printing the result when the same thing is run in the geekforgeeks online ide. Why is it doing this?
void getvert(Node* root,int hd,map<int,vector<int>>m){
if(root==NULL)return;
m[hd].push_back(root->data);
getvert(root->left,hd-1,m);
getvert(root->right,hd+1,m);
}
void verticalOrder(Node *root)
{
map<int,vector<int>>m;
int hd=0;
getvert(root,hd,m);
auto it=m.begin();
for(;it!=m.end();it++)
{
for (int i=0; i<it->second.size(); ++i)
cout<<it->second[i];
cout<<endl;
}
}
The function getvert accepts the last argument, m, as a value. Changes made to it in the function are made to a local copy of the object. Hence, you don't see any changes in verticalOrder.
Change getvert so that it accepts m as a reference.
void getvert(Node* root,int hd, map<int,vector<int>>& m) // Need reference argument
{
...
}
Related
I have a problem with the initialization with various parameters in my function.
It works if I have created an array int params [] = {...}. However, it doesn't work if I want to write the parameters directly into the function.
declaration (in the .h)
void phase_an(int led[]);
in the .cpp
void RS_Schaltung::phase_an(int led[])
{
for (size_t i = 0; i < LEN(led); i++) {
digitalWrite(led[i], HIGH);
}
}
if I try this way, it won't work. I would like it to be like that. But I couldn't find anything about it on the internet. ...:
in the Arduino sketch:
RS.phase_an(RS.ampelRot, RS.ampelGelb, ..... ); <--- is there a way to do it like that?
what amazes me is that it works this way:
int p_an [5] = {RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb};
...................
RS.phase_an (p_an);
does anyone have a suggestion?
There are several ways of making a function accepting a variable number of arguments here.
However, in your current code there is a problem: when you pass a native array of unknown size as argument of a function (e.g. void f(int a[])), the argument will be managed a pointer to an array, and there is no way inside this function to know the real length of that array. I don't know how LEN() is defined, but chances are high that it doesn't works well in your code.
A safer and more practical alternative is to use a vector<int> instead:
#include <iostream>
#include <vector>
using namespace std;
void f(const vector<int>& a){
for (int i=0; i<a.size(); i++) {
cout<<a[i]<<" ";
}
cout<<endl;
}
int main() {
vector<int> test={1,2,3,4};
f(test);
f({1,2,3,4});
return 0;
}
In this case, you can pass your multiple values between bracket in the function call (e.g. ({RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb})and C++ will automatically convert it to a vector.
This is part of a debugging assignment that I've been stuck on for days. I'm not as much looking for an answer as much as I'm looking for where to look to find the answer.
I have a function that takes an int as a parameter, and the test uses that function to calculate the sum of the range (0,n]. My problem is that I am new to C++ and have exhausted my knowledge of where to look to solve this. Any help would be greatly appreciated.
Also, it goes without saying that I cannot modify the test file.
Header.h
bool getNum(int n);
Header.cpp:
bool getNum(int n)
{
n = n + 1;
if (n < 10)
{
return true;
}
else
{
return false;
}
}
Test.cpp
int n = 0;
int sum = 0;
while (getNum(n) && n)
{
sum += n;
}
CHECK(sum == 45);
My problem is that I have no way of getting n to be true to pass the logical &&, so the test never visits the inside of the while loop.
You can change the value of an argument to a function, by taking that argument as a reference:
bool getNum(int &n) // note the reference parameter
{
// changes to n are visible to the caller of this function
}
You have to change the declaration of getNum to match as well, of course.
Note that there is no change to the calling code.
Here's a demo of a working example.
i did exactly what the pseudo code told me in the book introduction to algorithms and it didn't work
there are two parts that i dont really understand
1-how do u make a recursive function that is a void i mean shouldnt a recursive function always return the last step then what is before it .. it's a void so how would it preform the task
2-merg_sor() was called twice in one function .. do u call that nested recursion ?or what ?? .. and how does it affect the merg function
#include <iostream>
#include <vector>
using namespace std;
void Merg(vector<int> Arr,int start,int middle,int end)
{
std::vector<int> left;
std::vector<int> right;
for(int i =start;i<(end-start);i++)
{
if (i <middle)
{
right.push_back(Arr.at(i));
}
else
{
left.push_back(Arr.at(i));
}
}
int j=0;
int k=0;
for(int i =start;i<(end-start);i++)
{
if(right.at(j)<=Arr.at(i))
{
Arr.at(i)=right.at(j);
j++;
}
else
{
Arr.at(i)=left.at(k);
k++;
}
}
}
void Merg_sort(vector<int> Arr,int start,int end)
{
if (start <end)
{
int middle = (start+end)/2;
Merg_sort(Arr,start,middle);
Merg_sort(Arr,middle+1,end);
Merg(Arr,start,middle,end);
}
}
int main()
{
vector<int> x;
for (int i =0;i<8;i++){x.push_back(i);}
x.at(2)=8;
Merg_sort(x,0,7);
}
1-how do u make a recursive function that is a void i mean shouldnt a recursive function always return the last step then what is before it .. it's a void so how would it preform the task
A function can have side effects. It means, that a function can modify the state of the program. A void function always works by side effects. A void function that doesn't have side effects is completely useless. Whether the function is recursive makes no difference to this question.
2-merg_sor() was called twice in one function .. do u call that nested recursion ?or what ??
I'm not sure if it is commonly used term, but I would describe it as multi-branched recursion.
2 .. and how does it affect the merg function
It doesn't, because it has no side effects.
i did exactly what the pseudo code told me
Perhaps you didn't interpret the pseudo code correctly. Perhaps the arguments are implicitly references in the pseudo-language that you're reading such as they are in languages like python.
cliques is my class object. All my class commands work when I use them in my main but for some reason I cannot make changes to my heaps or stacks through my functions. I tried using reference markers on my function parameters but still I'm having ussues. Maybe I've done the reference incorrectly. Does anyone have any ideas what I might be doing wrong?
This is one of my functions:
void UpdateTopK(cliques C, vector<cliques> minheap) {
if (C.getclique_size() < CliqueSize) {
return;
}
else if (minheap.size() < Solutions) {
minheap.push_back(C);
push_heap(minheap.begin(), minheap.end(), min_iterator());
}
else if (minheap.size() == Solutions and C.getMaxclique_prob() > minheap.front().getMaxclique_prob()) {
pop_heap(minheap.begin(), minheap.end(), min_iterator());
minheap.pop_back();
minheap.push_back(C);
push_heap(minheap.begin(), minheap.end(), min_iterator());
}
This is part of my main:
stack <cliques> cstack;
vector<cliques> max_heap;
make_heap(max_heap.begin(), max_heap.end(), max_iterator());
vector<cliques> min_heap;
make_heap(min_heap.begin(), min_heap.end(), min_iterator());
for (int i = 0; i < 5; i++) {
cliques temp(i);
cstack.push(temp);
}
while (!cstack.empty()) {
cliques temp = cstack.top();
cstack.pop();
bool pruned = GenerateChildren(temp, min_heap, max_heap, cstack, graph);
if (!pruned) {
UpdateTopK(temp, min_heap);
}
}
You are passing arguments by value, this implies that parameters are copied before being passed to the function.
So every modification inside a method refers to the local copy only. Try passing values by references, eg:
void UpdateTopK(cliques& C, vector<cliques>& minheap)
^ ^
Mind that an object that needs to be passed to a function without copy and without being edited should be passed by const T& to specify this.
Here I have written some code to get the square of a number from a function, but the return statement is not working as desired by me, it is giving me the same number which I have entered, I want to know the reason behind this, please if any one can explain this to me...
#include<iostream>
#include<conio.h>
using namespace std;
int square(int &i);
int main()
{
cout<<"enter the number whose square you want to find";
int a;
cin>>a;
square(a);
cout<<"the square of the number is"<<a;
_getch();
return 0;
}
int square(int &i)
{
return i*i;
}
You're ignoring the returned value. You should store it as:
int value = square(a);
cout<<"the square of the number is "<< value;
Also, as the type is just integral type, passing by reference doesn't give you much advantage. I would suggest to use pass by value for its readability sake:
int square(int i)
{
return i*i;
}
--
Or in case if you're experimeting with reference, and trying to learn it, then in that case I would say that you've to store the result of product in the argument itself, as:
int square(int &i)
{
i = i * i; //this updates i here, and at the call site as well
return i;
}
Or simply do this:
int square(int &i)
{
return i = i*i; //multiply, update, and return - all in one statement!
}
You do not obtain the result.
Your line should be:
a = square(a);
to fetch the result from the function.
The other possibility would be to write in the function
int square(int &i)
{
i = i * i;
return i;
}
The latter will alter the variable you passed to the function which justifies passing a reference.
To make it clear you want to alter the variable do something like:
void square(int &i)
{
i = i * i;
}
You see there is no return involved but it will alter the variables value.
You have a choice:
Modify the parameter you pass in, or
Return a value and assign it to something in the calling scope.
What you are doing in square is the second option. You seem to want the first.
If what you really want is to modify the passed-in value, then what you need is this:
void square(int &i)
{
i = i*i;
}
Either do it this way:
a = Square (a) ; // in main()
...
int Square (int i) // Pass by value -- doesn't change a in main
{
return i * i ;
}
or do it this way:
Square (a) ; // in main()
...
void Square (int& i) // Pass by reference -- changes a in main
{
i = i * i ; // No need for a return value
}
Make sure you understand the difference before you program anything else!
Judging by your comments on the answers, you've misunderstood what passing by reference does OR you've misunderstood return.
I'm assuming you're thinking that the variable i will be updated in your program. However, this is not the case. If you did something like...
i = i*i;
then yes, you would be correct. However, you did not assign any value to i, you simply multiplied it by itself and returned the result. Also, if you truly wanted to make this work based on a reference, there would be no need to return anything, as the variable would be updated via the reference.