I am writing a program with a function that includes a long loop. I need this function to return a value when each loop is done, to send this value to output, in order to follow the progression. But I don't know how to do it in easy way.
The function is like follow:
1 2 3 4 5 6 7 8 9
int goC()
{
... // some local value definition
for(int i = 0; i < 1000; i++)
{
... // a lot of calculations done here
return i; // -> return the value after each loop is done
}
}
Here it only returns one value, i = 0. Clearly it's wrong.
Could anyone please help me with it? Thanks a lot!
#include <iostream>
#include <functional>
int foo( int n, std::function< void(int) > notify )
{
int sum = 0 ;
for( int i = 1 ; i < n ; ++i )
{
sum += i*i ;
notify(sum) ;
}
return sum ;
}
int main()
{
constauto report_progress = [] ( int s )
{ std::cout << "intermediate value returned: " << s << '\n' ; };
foo( 10, report_progress ) ;
}
instead of having the loop occur in the function, the loop needs to be outside of the function, so that the function only gets called once every iteration of the loop.
Thanks for the replies.
@JLBorges: could you please explain the report_progress? is it a lambda expression ?
@pogrady: too complicated to put the loop outside... about returning a pointer to int array, do you mean to define an array of values of i to control the loop, and return the pointer? Could you make it clearer please?
#include <stdio.h>
int foo( int n, void (*notify)(int) )
{
int sum = 0 ;
for( int i = 1 ; i < n ; ++i )
{
sum += i*i ;
notify(sum) ;
}
return sum ;
}
void report_progress( int s )
{ printf( "intermediate value returned: %d\n", s ) ; }
int main()
{
foo( 10, report_progress ) ;
}
@pogrady: ok. but, it seems that this function doesn't return the value of "x" at the same time as "x"'s value changes in the loop. am I right?
@JLBorges: actually I need the return value and send it to a "progress bar" of Qt, to let the progress bar show the progression. the code will look like:
1 2
constauto report_progress = [] ( int s )
{ ui.progressBar->setValue(s) ; };
ui is a kind of local pointer of Gui, setValue is a function of Qt to give value to the bar.
But this cannot work with lamdba expression. How can I rewrite it in normal form?
I think I don't know Qt very well, that's why I have tried all these solutions, it can be compiled, but it doesn't work on GUI.
However, when I use a normal form (means not lambda), the Gui can show the value returned. the only problem was just I could not get the number of loop to be updated at the same time as the loop progresses.
Is there is simple way to get this? just make the function return its loop value in real time? then I do ui->progressBar->setValue(s) each times while the value changes. thanks.
Then you want to use the lambda expression to update the value of the progress bar, or pass a function pointer to the function. Its essentially the same thing.