我想超載迭代器的「+」操作符列表類,像問題對運營商+隨機訪問迭代器的過載,在模板
list<double>::iterator operator+(const list<double>::iterator& it, int n)
這種運作良好。然而,當我嘗試實現它作爲模板,像
template<class T>
typename list<T>::iterator operator+(const typename list<T>::iterator& it, int n)
我有錯誤味精一樣,
no match for 'operator+' in 'it + small_index'
想不通的原因...
代碼附加
#include<iostream>
#include<list>
using namespace std;
template<class T>
ostream& operator<< (ostream& os, const list<T>& l)
{
typename list<T>::const_iterator i = l.begin();
for (;i!=--l.end();i++)
os<<*i<<";";
os<<*i<<endl;
return os;
}
template<class T> //this is where it goes WRONG.
//If don't use template, delete "typename", T->double, runs well
typename list<T>::iterator operator+(const typename list<T>::iterator& it, int n)
{
typename list<double>::iterator temp=it;
for(int i=0; i<n; i++)
temp++;
return temp;
}
template <class T>
void small_sort(list<T>& l)
{
int n = l.size();
typename list<T>::iterator it = l.begin();
for(int i=0; i<n-1; i++)
{
//Find index of next smallest value
int small_index = i;
for(int j=i+1; j<n; j++)
{
if(*(it+j)<*(it+small_index)) small_index=j;
}
//Swap next smallest into place
double temp = *(it+i);
*(it+i) = *(it+small_index);
*(it+small_index)=temp;
}
}
int main()
{
list<double> l;
l.push_back(6);
l.push_back(1);
l.push_back(3);
l.push_back(2);
l.push_back(4);
l.push_back(5);
l.push_back(0);
cout<<"=============sort the list=============="<<endl;
small_sort(l);
cout<<l;
return 0;
}
爲什麼不使用'std :: advance'而不是重寫? – Naveen
由於列表迭代器不是隨機訪問,標題相當具有誤導性。爲列表迭代器提供'operator +'會鼓勵使用低效的算法(這就是爲什麼標準沒有這樣的算子)。 –