@cire +1
@Dinh Hung: If you are not certain that every character in the string is a digit, you would want to check that first before subtracting '0'. Something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string test = "123456789";
{
for( char ch : test ) // for each character in the string
{
// if it is a digit, get the integer value of the digit
// if it is not a digit, zero (a la atoi).
const int x = std::isdigit(ch) ? ch - '0' : 0 ;
std::cout << x << ' ' ;
}
std::cout << '\n' ;
}
}
|
> It seem too hard but it is what I need. I will read and try it more and more.
It is not as hard as it appears at first sight if you take it one small step at a time.
Let us say, we have a function:
int function_one( int a, int b ) ;
We can easily write a function which takes no parameters, but calls
function_one(10,5) and returns the result.
1 2 3 4
|
int bound_function()
{
return function_one( 10, 5 ) ;
}
|
The implementation of
bound_function() has these pieces of information:
a. the function to be called is
function_one()
b. the first argument to be passed is the integer 10.
c. the second argument to be passed is the integer 5.
d. the result is an integer
std::bind()
is a generalisation of this idea:
a. we have a function (callable object)
b. we also have one or more specific arguments to be passed to the function
We want to create a new callable object which will call the original function with the stored arguments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
#include <functional>
int function_one( int a, int b )
{
const int result = a*a + b*b ;
std::cout << "function_one( " << a << ", " << b << " ) => " << result << '\n' ;
return result ;
}
double function_two( double a, double b, double c )
{
const double result = a + b - c ;
std::cout << "function_two( " << a << ", " << b << ", " << c << " ) => " << result << '\n' ;
return result ;
}
int main()
{
int x = 10 ;
int y = 5 ;
function_one( x, y ) ; // function_one( 10, 5 ) => 125
// f1 is a callable object that can be called with no arguments
// f1() would call function_one(10,5)
const auto f1 = std::bind( function_one, 10, 5 ) ;
f1() ; // function_one( 10, 5 ) => 125
// f2() would call function_one(3,8)
const auto f2 = std::bind( function_one, 3, 8 ) ;
f2() ; // function_one( 3, 8 ) => 73
// f3() would call function_two( 3.1, 28, 5.2 )
const auto f3 = std::bind( function_two, 3.1, 28, 5.2 ) ;
f3() ; // function_two( 3.1, 28, 5.2 ) => 25.9
}
|
http://coliru.stacked-crooked.com/a/b079d0543f52fd55
Once you have grasped this - you are comfortable with using
std::bind() to bind arguments to functions, and then call the bound function with no arguments - make a post accordingly, and we cam move on to the next small step.