我正在尝试使用binary_function向量进行变换调用。并出现错误。
代码:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v1 = {1, 2, 10, 23, 13};
vector<int> v2 = {10, 2, 4, -1, 3};
vector<int> result(v1.size());
plus<int> f1;
minus<int> f2;
multiplies<int> f3;
vector<binary_function<int, int, int>> funcs = {f1, f2, f3};
for (auto func: funcs) {
transform(v1.begin(), v1.end(), v2.begin(), result.begin(), func);
for (auto value: result) { cout << value << " "; }
cout << endl;
}
return 0;
}
g++ 返回错误:
In file included from /usr/include/c++/8/algorithm:62,
from test.cpp:1:
/usr/include/c++/8/bits/stl_algo.h: In instantiation of ‘_OIter std::transform(_IIter1, _IIter1, _IIter2, _OIter, _BinaryOperation) [with _IIter1 = __gnu_cxx::__normal_iterator<int*, std::vector<int> >; _IIter2 = __gnu_cxx::__normal_iterator<int*, std::vector<int> >; _OIter = __gnu_cxx::__normal_iterator<int*, std::vector<int> >; _BinaryOperation = std::binary_function<int, int, int>]’:
test.cpp:19:67: required from here
/usr/include/c++/8/bits/stl_algo.h:4343:25: error: no match for call to ‘(std::binary_function<int, int, int>) (int&, int&)’
*__result = __binary_op(*__first1, *__first2);
~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
为什么?
我读了std::binary_function - 与调用不匹配?但我无法理解答案:
std::binary_function only contains typedefs for argument and return types. It was never intended to act as a polymorphic base class (and even if it was, you'd still have problems with slicing).
为什么?
替换 std::binary_function 的实例。这应该按预期工作,没有任何编译错误。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v1 = {1, 2, 10, 23, 13};
vector<int> v2 = {10, 2, 4, -1, 3};
vector<int> result(v1.size());
auto f1 = [](int a, int b) { return a + b; };
auto f2 = [](int a, int b) { return a - b; };
auto f3 = [](int a, int b) { return a * b; };
vector<decltype(f1)> funcs = {f1, f2, f3};
for (auto func : funcs) {
transform(v1.begin(), v1.end(), v2.begin(), result.begin(), func);
for (auto value : result) {
cout << value << " ";
}
cout << endl;
}
return 0;
}