[英]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 );
在'='我得到错误:
Error:no operator "=" matches these operands
我知道一旦pred解析为true,find_if就会返回一个迭代器,那么交易是什么?
我们只能猜测错误,因为你只提供了一半的问题。
假设d是mapType
和isalnum的正确版本
问题是函子正在将一个对象传递给mapType :: value_type(这是地图和所有容器存储它们的值的方式)。 对于map,value_type实际上是实际实现为std :: pair <Key,Value>的键/值对。 所以你需要使用isalnum()来测试对象的第二部分。
在这里,我将该翻译包含在另一个可以由find_if使用的函数isAlphaNumFromMap中
#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() );
}
如果d
是map
,则问题在于您尝试使用isalnum
。
isalnum
采用单个int
参数,但find_if
调用的谓词接收map::value_type
。 这些类型不兼容,所以你需要一些能使find_if
适应`isalnum的东西。 比如这样:
#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 );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.