gpt4 book ai didi

c++ - 编写简单的 STL 泛型函数的问题

转载 作者:行者123 更新时间:2023-11-30 00:41:39 25 4
gpt4 key购买 nike

我正在自学如何使用迭代器创建通用函数。作为 Hello World 步骤,我编写了一个函数来取给定范围内的平均值并返回值:

// It is the iterator to access the data, T is the type of the data.
template <class It, class T>
T mean( It begin, It end )
{
if ( begin == end ) {
throw domain_error("mean called with empty array");
}

T sum = 0;
int count = 0;
while ( begin != end ) {
sum += *begin;
++begin;
++count;
}
return sum / count;
}

我的第一个问题是:计数器使用int可以吗,如果数据太长会溢出吗?

我从以下测试工具中调用我的函数:

template <class It, class T> T mean( It begin, It end );

int main() {
vector<int> v_int;
v_int.push_back(1);
v_int.push_back(2);
v_int.push_back(3);
v_int.push_back(4);

cout << "int mean = " << mean( v_int.begin(), v_int.begin() ) << endl;;

return 0;
}

编译时出现错误:

error: no matching function for call to ‘mean(__gnu_cxx::__normal_iterator<int*,    
std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*,
std::vector<int, std::allocator<int> > >)’

谢谢!

最佳答案

  1. 您可以使用 iterator_traits<It>::difference_type而不是 int 以确保它不会溢出。这是 std::distance 返回的类型.

  2. 你的编译错误是因为编译器无法确定类型T

这是因为编译器首先只查看函数的声明。而如果只看声明,是无法知道T是什么的。与第一个问题一样,您可以使用 iterator_traits。

你可以像这样:

template <class It> 
typename std::iterator_traits<It>::value_type mean( It begin, It end )
{
if ( begin == end ) {
throw domain_error("mean called with empty array");
}

typename std::iterator_traits<It>::value_type sum = 0;
typename std::iterator_traits<It>::difference_type count = 0;
while ( begin != end ) {
sum += *begin;
++begin;
++count;
}
return sum / count;
}

关于c++ - 编写简单的 STL 泛型函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3310753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com