我想创建一个函数来vector<int>
运行他的所有元素并根据我选择的特定运算符“求和”它们。
例如,v1 = [3,6,7]
所以我可以通过这个函数来计算 - of 3+6+7
etc ..3-6-7
3*6*7
为此我做了-
#include <iostream>
#include <vector>
using namespace std;
#define OPERATOR(X,Y,OP) X #OP Y
template<T>
int allVectorWithOperator(vector<int> &myVector, T) {
vector<int>::iterator it;
vector<int>::iterator oneBeforeFinal;
oneBeforeFinal = myVector.end();
oneBeforeFinal -= 2;
int sum = 0;
for (it = myVector.begin(); it <= oneBeforeFinal; it++) {
sum = OPERATOR(*(it),*(it+1),T);
}
return sum;
}
int main() {
vector<int> myVector;
myVector.push_back(3);
myVector.push_back(6);
myVector.push_back(7);
cout << "run over all the vector with * is :" << allVectorWithOperator(myVector,*)<<endl;
// here I want to get 3*6*7
}
在模板的这种情况下,我控制得不是很好,所以你可以看到这段代码不起作用,但我想你明白我的目标是什么。我怎样才能修复它以正常工作?
编辑:
根据我得到的 2 答案,我将代码部分更改为 -
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
template<typename T>
int allVectorWhitOperator(vector<int> &myVector, const T& func) {
int sum = std::accumulate(myVector.begin(), myVector.end(), 1, func);
return sum;
}
int main() {
vector<int> myVector;
myVector.push_back(3);
myVector.push_back(4);
myVector.push_back(6);
cout << "accumulate the vector with * is :"
<< allVectorWhitOperator(myVector, std::multiplies<int>()) << endl;
}
它工作正常!确实我got accumulate the vector with * is :72