简体   繁体   English

无法分配给mapType :: const_iterator? (“没有运营商=匹配”)

[英]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 operator "=" matches these operands

I know that find_if returns an iterator once the pred resolves to true, so what is the deal? 我知道一旦pred解析为true,find_if就会返回一个迭代器,那么交易是什么?

The documentation for std::find_if 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 假设d是mapTypeisalnum的正确版本

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). 问题是函子正在将一个对象传递给mapType :: value_type(这是地图和所有容器存储它们的值的方式)。 For map the value_type is actually a key/value pair actually implemented as std::pair<Key,Value>. 对于map,value_type实际上是实际实现为std :: pair <Key,Value>的键/值对。 So you need to get the second part of the object to test with isalnum(). 所以你需要使用isalnum()来测试对象的第二部分。

Here I have wrapped that translation inside another functor isAlphaNumFromMap that can be used by find_if 在这里,我将该翻译包含在另一个可以由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() );

}

If d is a map , then the problem is with your attempted use of isalnum . 如果dmap ,则问题在于您尝试使用isalnum

isalnum takes a single int parameter, but the predicate called by find_if receives a map::value_type . isalnum采用单个int参数,但find_if调用的谓词接收map::value_type The types are not compatible, so you need something that adapts find_if to `isalnum. 这些类型不兼容,所以你需要一些能使find_if适应`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 );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM