我试图找到列表中对象的出现次数:
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
?显然,我不是迭代器(指针)而不是复杂对象吗?
答案 0 :(得分:3)
您可以通过以下两种方式之一简化代码:
使用std::count
或其中一个变体进行计数。所以:
return std::count(container.begin(), container.end(), element);
或者只是像你已经做的那样使用一个简单的for循环,但是从头到尾迭代它并自己进行计数,如下所示:
int count = 0;
for (ContainerType::const_iterator it = container.begin(); it != container.end(); ++it)
{
if (*it == element) ++count;
}
return count;
由于你已经在使用部分STL,我建议使用第一种方法。
答案 1 :(得分:1)
似乎Iterator没有重载operator +(int),请尝试:
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, 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;
}
我希望这会奏效。
答案 2 :(得分:0)
它是一个没有随机访问操作的列表迭代器。你想做的事:
++i;
i = std::find (i, container.end(), element);