Reputation: 1260
int CRegister::CountCars(const string& name, const string& surname)const{
const pair<string,string> wholename(name,surname);
vector<CDriver>::iterator Diterator=lower_bound(m_Drivers.begin(),m_Drivers.end(),wholename);
if (Diterator<m_Drivers.end()){
if(Diterator->m_name.compare(wholename.first)!=0 || Diterator->m_surname.compare(wholename.second)!=0) return 0;
return Diterator->m_DriversNumber;
}
return 0;
}
Hello, when I try to compile this, it throws error on the third line:
"conversion from ‘__gnu_cxx::__normal_iterator<const CDriver*, std::vector<CDriver> >’ to non-scalar type ‘std::vector<CDriver>::iterator {aka __gnu_cxx::__normal_iterator<CDriver*, std::vector<CDriver> >}’ requested
When I set the function CountCars as a non-const, it compiles without problems. What should I change to fix this? (the function has to be const)
Upvotes: 0
Views: 135
Reputation: 42924
Consider using a const_iterator
, e.g.
vector<CDriver>::const_iterator Diterator
= lower_bound(m_Drivers.begin(), m_Drivers.end(), wholename);
If you can compile in C++11/14, using auto
helps as well:
auto Diterator = lower_bound(m_Drivers.begin(), m_Drivers.end(), wholename);
(With auto
, the compiler deduces the correct iterator type, without requiring you to correctly "spell" it explicitly in code.)
Upvotes: 1
Reputation: 7447
To solve your problem you have to use a const_iterator
The reason is the following : The method is marked const, which means that the method itself is not going to change state of the object instance upon which the method is invoked.
Therefore within a const method you cannot call any other method on the same object that is not marked const. Because of course that new call does not garantee that it is const so can the first method not claim to be const anymore.
by declaring the iterator const you are going to use the const version of lower_bound.
Upvotes: 3
Reputation: 122381
Try using a const_iterator
:
vector<CDriver>::const_iterator Diterator
// ^^^^^^
Upvotes: 1