简体   繁体   English

标准迭代器分配错误

[英]Std iterator assignment error

Please bear with me if the question is silly. 如果这个问题很愚蠢,请忍受我。

The following are defined in a header file : 头文件中定义了以下内容:

typedef char NAME_T[40];

struct NAME_MAPPING_T
{
    NAME_T englishName;
    NAME_T frenchName;
};

typedef std::vector<NAME_MAPPING_T> NAMES_DATABASE_T;

Later the need comes that a particular english name be found : 后来需要找到一个特定的英文名称:

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; } );

This code (which I copy-pasted to be honest) compiles, but if I want to check the value returned by find_if(), like this : 这段代码(老实说,我复制粘贴了)可以编译,但是如果我想检查find_if()返回的值,像这样:

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

the code will NOT compile ! 该代码将无法编译!

In effect the line it = std::find_if(...) will return the error : 实际上, 的行= 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)

What is wrong ? 怎么了 ?

Thanks for your time. 谢谢你的时间。

const NAMES_DATABASE_T *wordsDb;

Your wordsDb is const, therefore wordsDb->begin() returns a const iterator, therefore find_if returns a const iterator as well. 您的wordsDb是const,因此wordsDb->begin()返回const迭代器,因此find_if返回const迭代器。 You're trying to assign that const iterator to the non-const NAMES_DATABASE_T::iterator it , hence the error. 您正在尝试将该常量迭代器分配给非常量NAMES_DATABASE_T::iterator it ,因此出现错误。

You can use NAMES_DATABASE_T::const_iterator to get a const iterator. 您可以使用NAMES_DATABASE_T::const_iterator获取const迭代器。 And you should use std::string instead of those char buffers, unless there are some rare circumstances that require otherwise. 并且,除非有一些其他特殊情况,否则应使用std::string代替那些char缓冲区。

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

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