我試圖找到列表中的一個對象的出現次數對象的出現次數:統計列表中的
class Complex{
double re, im;
public:
Complex (double r, double i):re(r), im(i){}
Complex(){re = im = 0;}
friend bool operator == (Complex, Complex);
};
bool operator == (Complex a, Complex b){
return a.re == b.re and a.im == b.im;
}
template <class ContainerType, class ElementType>
int const count (ContainerType const & container, ElementType const & element){
int count = 0;
typename ContainerType::const_iterator i = std::find (container.begin(), container.end(), element);
while (i != container.end()){
++count;
i = std::find (i + 1, container.end(), element);
}
return count;
}
int main(){
std::list <Complex> lc;
lc.push_front (Complex (1.2, 3.4));
std::cout << count (std::string("abhi"), 'a') << '\n';
std::cout << count (lc, Complex (1.2, 3.4)) << '\n';
return 0;
}
我得到這個錯誤與G ++ 4.5:
templatizedcharOccurences.c++: In function ‘const int count(const ContainerType&, const ElementType&) [with ContainerType = std::list<Complex>, ElementType = Complex]’:
templatizedcharOccurences.c++:51:44: instantiated from here
templatizedcharOccurences.c++:41:4: error: no match for ‘operator+’ in ‘i + 1’
templatizedcharOccurences.c++:22:9: note: candidate is: Complex operator+(Complex, Complex)
爲什麼它會抱怨i+1
?顯然,我不是一個迭代器(指針),而不是一個複雜的對象?
'iterator'!='pointer'。指針是一種特殊類型的迭代器。 –