Reputation:
The following code raises the no matching function for call to 'toupper' error (C++ 11):
string s("some string");
if (s.begin() != s.end())
{
auto it = s.begin();
it=toupper(it);
}
This code is from C++ primer, fifth edition, chapter 3, about "introducing iterators".
Do you know why this error?
Upvotes: 0
Views: 4353
Reputation: 131978
<string>
and <cctype>
.std::
(use say using namespace std
, but that is not a good idea).it
is not a character. It is an iterator into the string. Think of it as a pointer-like object. When you want to change a character pointed to by p
, you would say *p = do_something_with(*p)
, not p = do_something_with(p)
which would change the pointer.Thus if we write:
#include <iostream>
#include <cctype>
int main()
{
std::string s("some string");
if (s.begin() != s.end()) {
auto it = s.begin();
*it = std::toupper(*it);
}
}
then this compiles (GodBolt.org).
Upvotes: 1