在向量数组中编写一个可以给出最大值及其相应索引的函数并不困难,如下代码所示:
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));
}但是我不明白为什么我原来的实现有编译错误,我能做些什么来纠正它吗?
发布于 2013-10-14 12:45:29
您试图比较不同类型的迭代器,需要使用const_iterator作为weighting is const
std::vector<T>::const_iterator it = max_element(weighting.begin(),weighting.end());这就是为什么auto在C++11方面如此优秀的原因。
发布于 2013-10-14 12:46:47
向量有两种类型的迭代器,const_iterator和正则iterator,它们是不同的类型,因此不能从一种转换到另一种。
你应该换衣服
std::vector<T>::iterator it = ...至
std::vector<T>::const_iterator it = ...或者让编译器为您完成以下工作更好:
auto it = ...https://stackoverflow.com/questions/19360537
复制相似问题