あなたがC++ 11を持っている場合は、std::bind
を使用することができます。 1つの迅速な動きで各要素に5を追加することにより、ベクトルを変換し、この例を考えてみましょう:あなたの例については
#include <iostream>
using std::cout;
#include <functional>
using std::plus;
using std::bind;
using std::placeholders::_1;
#include <vector>
using std::vector;
#include <algorithm>
using std::transform;
int main()
{
vector<int> v {1, 3, 6};
//here we bind the value 5 to the first argument of std::plus<int>()
transform (v.begin(), v.end(), v.begin(), bind (plus<int>(), _1, 5));
for (int i : v)
cout << i << ' '; //outputs "6 8 11"
}
、私はこのようなそれに近い何かを書くことができました:
#include <iostream>
using std::cout;
#include <functional>
using std::bind;
using std::function;
using std::placeholders::_1;
void foo (function<double (double, double)> func) //take function object
{
//try to multiply by 3, but will do 2 instead
for (double i = 1.1; i < 5.6; i += 1.1)
cout << func (i, 3) << ' ';
}
double bar (double x, double y)
{
return x * y;
}
int main()
{
foo (bind (bar, _1, 2));
}
出力:
2.2 4.4 6.6 8.8 11
でも、私は何かをovercomplicatedている場合があります。実際にはstd::bind
とstd::function
の両方を使用していました。あなたがしたいがstd::bind
/std::function
を使用していない場合は
'std :: bind'をチェックしてください。関数内の1つ以上の引数に値をバインドすることができます。 – chris
ありがとう、私はこれをチェックします。 – vanna
あなたは 'のstd :: function'、その後、あなたはブースト同等物を使用することができます' 'で見つかったプレースホルダとの'のstd :: bind'のためのC++ 11のサポートを持っていない場合。 –
AJG85