c++ - 带宏的模板函数 - 在 vector 上累积

标签 c++ templates vector macros c-preprocessor

我想创建一个获取 vector<int> 的函数遍历他的所有元素并根据我选择的特定运算符对它们进行“求和”。

例如,v1 = [3,6,7]所以我可以通过这个函数计算 - 3+6+73-6-73*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

最佳答案

标准库已经有了中的操作<algorithm> <numeric> .

你可以使用

int sum = std::accumulate(MyVector.begin(), MyVector.end(), 0);

将所有元素相加。

如果你想计算产品(而不是使用默认的 operator+ ),你可以传递一个额外的参数

int product = std::accumulate(MyVector.begin(), MyVector.end(), 1,
                              std::multiplies<int>());

关于c++ - 带宏的模板函数 - 在 vector 上累积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12287768/

相关文章:

c++ - GRPC:如何打开 GRPC 分析宏 GPR_TIMER_BEGIN/GPR_TIMER_END

java - 尝试打印 vector 的平均值时出错

c++ - 以编程方式打印时,我可以为每个页面指定不同的页面大小吗?

c++ - 如何使读取功能不挂起?

c++ - 赋值运算符左边的三元条件运算符

javascript - 如何在使用 fastify 服务之前替换 Javascript 变量?

c++ - is_Detected 可以使用哪些类型的模板?

json - Opsworks实例启动失败: Status: start_failed: No such cookbook: apt

c++ - push_back 常量字符*

c++ - 为什么对 std::tuple 的 std::vector 进行排序比对 std::arrays 的 vector 排序更快?