标准迭代器分配错误

Std iterator assignment error

本文关键字:错误 分配 迭代器 标准      更新时间:2023-10-16

如果这个问题很傻,请耐心等待。

头文件中定义了以下内容:

typedef char NAME_T[40];
struct NAME_MAPPING_T
{
    NAME_T englishName;
    NAME_T frenchName;
};
typedef std::vector<NAME_MAPPING_T> NAMES_DATABASE_T;

后来需要找到一个特定的英文名称:

const NAMES_DATABASE_T *wordsDb;
string str;
std::find_if(   wordsDb->begin(), 
                wordsDb->end(), 
                [str](const NAME_MAPPING_T &m) -> bool { return strncmp(m.englishName, str.c_str(), sizeof(m.englishName)) == 0; } );

这段代码(老实说,我复制粘贴了它)可以编译,但如果我想检查find_if()返回的值,如下所示:

NAMES_DATABASE_T::iterator it;
it = std::find_if(blah ..)

代码将不会编译

实际上,这条线it=std::find_if(…)将返回错误:

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::_Vector_const_iterator<_Myvec>' (or there is no acceptable conversion)

怎么了?

谢谢你抽出时间。

const NAMES_DATABASE_T *wordsDb;

您的wordsDb是const,因此wordsDb->begin()返回一个const迭代器,所以find_if也返回一个常量迭代器。您正试图将该常量迭代器分配给非常量NAMES_DATABASE_T::iterator it,因此出现错误。

您可以使用NAMES_DATABASE_T::const_iterator来获取常量迭代器。您应该使用std::string而不是那些字符缓冲区,除非在一些罕见的情况下需要其他缓冲区。