c++ - 用于获取最大值及其在 vector 中的相应索引的模板函数

标签 c++ vector

编写一个可以为您提供最大值及其在 vector 数组中的相应索引的函数并不难,如下面的代码所示:

using namespace std;



std::vector<double> line_weighting;
line_weighting.push_back(22);
line_weighting.push_back(8);
line_weighting.push_back(55);
line_weighting.push_back(19);



std::vector<double>::iterator   it =  std::max_element(line_weighting.begin(),line_weighting.end());
int index = distance(line_weighting.begin(),it);
value = *it;

我对使用可以执行相同类型功能的模板的更通用的函数更感兴趣:

template<typename T>
     int max_with_index(const std::vector<T> &weighting, T &max_value)
     {
         std::vector<T>::iterator  it = max_element(weighting.begin(),weighting.end());
         max_value =   *it;
         return (std::distance(weighting.begin(),it));
     }

但是这个函数在VC2010中出现如下错误,无法编译:

Error   2   error C2782: 'iterator_traits<_Iter>::difference_type std::distance(_InIt,_InIt)' : template parameter '_InIt' is ambiguous 
Error   1   error C2440: 'initializing' : cannot convert from 'std::_Vector_const_iterator<_Myvec>' to 'std::_Vector_iterator<_Myvec>'

我知道如果我这样写这个函数,它就可以工作。

  template<typename T>
     int max_with_index(const std::vector<T> &weighting, T &max_value)
     {
        // std::vector<T>::iterator  it = max_element(weighting.begin(),weighting.end());
         auto  it= max_element(weighting.begin(),weighting.end());
         max_value =   *it;
         return (std::distance(weighting.begin(),it));
     }

但是我不明白为什么我的原始实现有编译错误,我可以做些什么来纠正它吗?

最佳答案

你正在尝试比较不同类型的迭代器,你需要使用 const_iterator 因为 weightingconst

std::vector<T>::const_iterator  it = max_element(weighting.begin(),weighting.end());

这就是 auto 在 C++11 中如此出色的原因。

关于c++ - 用于获取最大值及其在 vector 中的相应索引的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19360537/

相关文章:

c++ - 如何使用 std::string 作为 stxxl::map 中的键

c++ - Media Foundation 设置视频隔行扫描和解码

c++ - 删除链表结构的链表

scala - Scala 库方法 Vector.sorted 使用什么算法?

c++ - 如何将 vector 转换为数组

c++ - 在 CPP 中删除重叠对象

c++ - yaml-cpp 到 std::vector 迭代奇怪的行为

c++ - 逐行读取文本文件并计算比较运算符

C++ 检查类对象是否包含某个元素

android - ndk-build 输出 ‘error adding symbols. File in wrong format’