传递对模板的引用

passing reference to the templates

本文关键字:引用      更新时间:2023-10-16

现在我正在模板上工作。所以,我被困在以下问题中,这是用随机值填充向量的代码,然后计算其中有多少个奇数值:

#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <iterator>
#include <ctime>
using namespace std;
class Odd{
private:
    int c;
public:
    bool operator()(int x){return x%2!=0;}
};
template<typename T,typename Q>
int count_(T f1,T f2,Q& check){
    int count=0;
    while(f1!=f2)
    {
        count+=check(*f1);
        f1++;
    }
    return count;
}
int Rand(){
    return ((rand()%100)+1);
}
int main(){
    srand(time(0));
    vector<int> V(100);
    Odd O;
    generate(V.begin(),V.end(),Rand);
    cout<<count_(V.begin(),V.end(),O);
}

这工作得很好,但当我通过T&在参数中,它给出了error ..即

template<typename T,typename Q>
int count_(T& f1,T& f2,Q& check){
    int count=0;
    while(f1!=f2)
    {
        count+=check(*f1);
        f1++;
    }

我不知道为什么,因为这是对指针的引用,所以它会工作得很好…

正如AlchemicalApples在评论中指出的那样,V.begin()V.end()返回右值,只能绑定到const或右值引用。

实际上不需要通过引用传递迭代器——复制迭代器的成本很低。实际上,所有STL算法都是按值接受迭代器参数的。

实际上,你不应该通过引用传递迭代器,因为你的函数会修改它们,这是意料之外的(没有任何标准算法会这样做),如果你在代码中进一步使用这些迭代器,可能会导致错误。