c++ - passing reference to the templates -
nowadays m working on templates .so, got stuck in following problem code fills vector random values , count how many odd values in it:
#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); } this works fine when pass t& in arguments gives error ..i.e
template<typename t,typename q> int count_(t& f1,t& f2,q& check){ int count=0; while(f1!=f2) { count+=check(*f1); f1++; } i dont know why because reference pointer work fine ...plz ..thankx
as alchemicalapples pointed out in comment, v.begin() , v.end() return rvalues, can bound const or rvalue references.
you don't need pass iterators reference - cheap copy. in fact, stl algorithms take iterator arguments value.
actually, shouldn't ever pass iterators reference, because function modify them, unexpected (none of standard algorithms that) , lead errors if use these iterators further in code.
Comments
Post a Comment