简体   繁体   English

在模板函数中使用const迭代器

[英]use of const iterator in template function

I'm using template functions in order that it may work with list or vector of different numerical data types. 我正在使用模板函数,以便它可以与不同数值数据类型的列表或向量一起使用。 But one of them has an issue: 但是其中一个存在问题:

// This function should take 2 iterators of a vector/list and sum the elements between them
template <typename T >
double Sum1(typename T::const_iterator start, typename T::const_iterator end){
    double sum = 0;
    // For g++, "typename is needed before T::const_iterator"
    for(typename T::const_iterator I = start; I <= end;I++){
        sum += *I;
    }
    return sum;
}

in the main(), it is called like this: 在main()中,它的调用方式如下:

vector<double> b;// and it is pushed by numbers 1-9 later

cout<<Sum1(b.begin(), b.end())<<endl;

but the compiler gives me errors 但是编译器给我错误

no matching function for call to 'Sum1(std::vector::iterator, >std::vector::iterator)' 没有匹配的函数来调用'Sum1(std :: vector :: iterator,> std :: vector :: iterator)'

couldn't deduce template parameter 'T' 无法推断出模板参数“ T”

However, this function works fine: 但是,此功能可以正常工作:

// T can be vector<int>, list<double>, etc. 
template <typename T >
double Sum(T& values){
    double sum = 0;
    // For g++, "typename is needed before T::const_iterator"
    for(typename T::const_iterator I = values.begin(); I != values.end();I++){
        sum += *I;
    }
    return sum;
}

Any idea why this happens? 知道为什么会这样吗? How should I revise the first function so it can take 2 iterators of a vector/list and calculate the sum in between? 我应该如何修改第一个函数,以便它可以使用一个向量/列表的2个迭代器并计算它们之间的总和?

Instead of templatizing on the container type, templateize on the iterator. 无需在容器类型上模板化,而在迭代器上进行模板化。 And don't restrict your users to const_iterator -- any iterator should do is you don't actually modify the contents through the iterator: 并且不要将您的用户限制为const_iterator -任何迭代器都应该做的是您实际上没有通过迭代器修改内容:

template <typename Iter> double Sum1(Iter start, Iter end)

By doing this you can also use any type that is dereferenceable and incrementable -- such as a simple pointer. 通过这样做,您还可以使用可取消引用和可递增的任何类型,例如简单的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM