Can't assign to mapType::const_iterator? ("no operator = matches")
typedef map<string,int> mapType;
mapType::const_iterator i;
i = find_if( d.begin(), d.end(), isalnum );
at the '=' i am getting the error:
Error:no o开发者_Python百科perator "=" matches these operands
I know that find_if returns an iterator once the pred resolves to true, so what is the deal?
The documentation for std::find_if
We can only guess at the error as you have only provided half the problem.
Assuming d is mapType
and the correct version of isalnum
The problem is that the functor is being passed an object to mapType::value_type (which is how the map and all containers store their value). For map the value_type is actually a key/value pair actually implemented as std::pair<Key,Value>. So you need to get the second part of the object to test with isalnum().
Here I have wrapped that translation inside another functor isAlphaNumFromMap that can be used by find_if
#include <map>
#include <string>
#include <algorithm>
// Using ctype.h brings the C functions into the global namespace
// If you use cctype instead it brings them into the std namespace
// Note: They may be n both namespaces according to the new standard.
#include <ctype.h>
typedef std::map<std::string,int> mapType;
struct isAlphaNumFromMap
{
bool operator()(mapType::value_type const& v) const
{
return ::isalnum(v.second);
}
};
int main()
{
mapType::const_iterator i;
mapType d;
i = std::find_if( d.begin(), d.end(), isAlphaNumFromMap() );
}
If d
is a map
, then the problem is with your attempted use of isalnum
.
isalnum
takes a single int
parameter, but the predicate called by find_if
receives a map::value_type
. The types are not compatible, so you need something that adapts find_if
to `isalnum. Such as this:
#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
typedef map<string,int> mapType;
bool is_alnum(mapType::value_type v)
{
return 0 != isalnum(v.second);
}
int main()
{
mapType::const_iterator i;
mapType d;
i = find_if( d.begin(), d.end(), is_alnum );
}
精彩评论