Reputation: 241
I am trying to test an example of search()
from Stroustup's book.
string quote("why waste time learning, when ignorance is instantaneous?");
bool in_quote(const string& s){
char* p = search(quote.begin(), quote.end(), s.begin(), s.end());
return p != quote.end();
}
void test(){
bool b1 = in_quote("learning"); // b1=true
bool b2 = in_quote("lemming"); // b2=false
}
But I get the following error:
error C2440: 'initializing' : cannot convert from
'std::_String_iterator<_Elem,_Traits,_Alloc>' to 'char *'
It looks like the return type is not right. I also tried string::iterator
, and got the same error. So, what should be the right type, is it supposed to be the iterator type of the container? Thanks
Upvotes: 3
Views: 708
Reputation: 308402
Early implementations of string
could easily have used char*
as their iterator type, allowing this incorrect code snippet to compile properly. Most modern implementations of string::iterator
have a proper class type and would not be convertible to char*
.
The signature for std::search
is:
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator1 search ( ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2 );
As you can see, the return type is the same as the type of the first two iterators passed to the function. In your case string::iterator
should have worked, unless there is some part of the code you did not show us that made quote
const
in which case you could use string::const_iterator
.
Upvotes: 1
Reputation: 2399
Per SGI documentation, the form of search
you are using has the signature:
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2);
Since your FowardIterator1
type is std::string::iterator
, your return type must be std::string::iterator
as well.
Upvotes: 0
Reputation: 263220
How about simply not caring about the return type? :)
bool in_quote(const string& s){
return search(quote.begin(), quote.end(), s.begin(), s.end()) != quote.end();
}
Upvotes: 4
Reputation: 29174
I tried the following
bool in_quote(const string& s){
string::iterator p = search(quote.begin(), quote.end(), s.begin(), s.end());
return p != quote.end();
}
And it did compile without error ...
Upvotes: 3
Reputation: 72519
You have a const string
, so it must be a const_iterator
:
string::const_iterator p = search(quote.begin(), quote.end(), s.begin(), s.end());
Upvotes: 1